Sunday, 18 December 2016

SharePoint list creation using REST api

This is a code blog to create a SharePoint List using REST API calls and jQuery scripting currently the only input is the list name and rest options are hard coded but can be easily be modified to fit your need
function ListCreation() {
var _listName = listName();
var listUrl = listNameShrink(_listName);
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists",
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.List' },
'AllowContentTypes': true,
'BaseTemplate': 100,
'ContentTypesEnabled': true,
'Description': 'List created Through REST',
'Title': listUrl,
'OnQuickLaunch': true
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
if (listUrl != _listName)
$.ajax({
url: data.d.__metadata.uri,
type: 'POST',
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": data.d.__metadata.etag
},
data: JSON.stringify({
'__metadata': { 'type': data.d.__metadata.type },
'Title': _listName
}),
success: function (dataP) {
$("#result1").removeClass("hidden").stop().show(0).text(_listName + " List is being Created with url as " + listUrl).hide(30000).mouseenter(function () { $(this).stop().show(0); }).mouseleave(function () { $(this).hide(30000) });
},
error: function (error) {
alert("error updating List name " + error);
}
});
else
$("#result1").removeClass("hidden").stop().show(0).text(_listName + " List is being Created " + listUrl).hide(30000).mouseenter(function () { $(this).stop().show(0); }).mouseleave(function () { $(this).hide(30000) });
},
error: function (error) {
alert("error creating List " + error);
}
});
}

The supporting functions for the above code are
function listName() {
var _listName = $("#ListName0").val();
return _listName;
}
function listNameShrink(_listName) {
var listNameWords = _listName.split(" ");
var listUri = "";
for (i = 0; i < listNameWords.length; i++) {
listUri += listNameWords[i].charAt(0).toUpperCase() + listNameWords[i].slice(1);
}
return listUri;
}

The second supportive function helps in removing spaces in the list name and capitalization of each words first letter(alphabet)
Please, do comment on any query related to the topic