Add content type to SharePoint List/Library using REST API

Add content type to SharePoint List/Library using REST API


Use this below code to add content type to SharePoint Library using REST API. For this you need to use the content type ID.

Below function will get the content type ID from content type name & we will pass the content type id to next function which will update content type to list/library.


var varContentTypeName = "Your Content Type name";
var Listname = "Your List name where you want to add content type";

//This will get the content type ID from content type Name
function getContentTypeID()
{
var deferred = $.Deferred();
    var isCurrentUserIsApprover = false;
var serverURL = _spPageContextInfo.webAbsoluteUrl;
var listURL = String.format("{0}/_api/web/AvailableContentTypes?$select=Name,Id,StringId&$filter=Name eq '"+varContentTypeName+"'",serverURL);
$.ajax({
url: listURL,
type: "GET",
async: false,
headers: {"Accept": "application/json;odata=verbose"},
cache: false,
success: function(data){
if($(data.d.results) != null)
{var varContentTypeId=data.d.results[0].StringId; addContentType(varContentTypeId);}
deferred.resolve();
},
error: function (err) {
alert(err.responseText);
deferred.reject(false);
}
});
return deferred.promise();
}

//this will add content type to the List/Library
function addContentType(varContentTypeId)
{
var deferred = $.Deferred();

var serverURL = _spPageContextInfo.webAbsoluteUrl;
var listURL = String.format("{0}/_api/web/lists/getbytitle('"+Listname+"')/ContentTypes/AddAvailableContentType",serverURL);
$.ajax({
url: listURL,
method: "POST",
data: JSON.stringify({            
            "contentTypeId": varContentTypeId            
        }),
headers: { 'accept': 'application/json;odata=verbose',
               "content-type": "application/json;odata=verbose",
               "X-RequestDigest": jQuery("#__REQUESTDIGEST").val() 
},
success: function(data){
alert('Content Type Added!');  
deferred.resolve();
},
error: function (err) {
alert(err.responseText);
deferred.reject();
}
});

return deferred.promise();
}

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

A type named 'SP.Data. could not be resolved by the model error