Search This Blog

Monday, July 27, 2015

Create List View using SharePoint REST API


function createView(ListName, query )
{

var bodyContent = "{ '__metadata': { 'type': 'SP.View' }, 'Title': 'View Name', 'PersonalView': true, 'ViewQuery':'" + query + "' }";

var viewUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('"+ListName+"')/views"

 var executor;  executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);  executor.executeAsync({ url: viewUrl,

method: "POST",

body: bodyContent,

headers: { 

"accept": "application/json;odata=verbose",

"content-type": "application/json;odata=verbose"

},

success: function (results) { alert("View Created.") },

error: function (error) { alert("Error in view creation.") }

});

}

Call this function you have to pass two parameter ListName and query.
ListName : This is name of list in which you want to create view.

Query : You have to pass CAML Query base on which filter is set and your view is created. Like

 '<Where><Eq><FieldRef Name=\"'Title'\" /><Value Type=\"Text\">' + TitleVar +'</Value></Eq</Where>';




You can customize your view but adding more attribute in body.

This code create a personal view because i set 'PersonalView' : true. If you want to create public view than set it to false. 

var bodyContent = "{ '__metadata': { 'type': 'SP.View' }, 'Title': 'View Name', 'PersonalView': true, 'ViewQuery':'" + query + "' }";


For more detail check https://msdn.microsoft.com/en-us/library/office/dn531433.aspx#bk_View

Note : 

1. Please make sure that you have loaded SP.RequestExecutor.js script file. To load script file

var scriptbase = _spPageContextInfo.webAbsoluteUrl+ "/_layouts/15/";

$.getScript(scriptbase + "SP.RequestExecutor.js", yourFunctionName);


2. You have proper permission to create views.

No comments:

Post a Comment