In this blog I would like to share the code for adding the content type in existing SharePoint list using SP hosted app model.
Write the below code on your *.js file,
-
- var context = SP.ClientContext.get_current();
-
- $(document).ready(function () {
- console.log("page loading...");
- $("#btnCreate").click(function () {
- addContenType();
- });
- });
-
-
- function addContenType() {
-
- var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
-
- var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
-
- var currentWEB = appCtxSite.get_web();
-
- var lists = currentWEB.get_lists();
-
- var rootWeb = appCtxSite.get_site().get_rootWeb();
-
- var allContentTypeColl = rootWeb.get_contentTypes();
-
- context.load(rootWeb);
- context.load(allContentTypeColl);
- context.load(lists);
- context.executeQueryAsync(function () {
- var CTypeID;
- var contentTypeName = "customTestCT";
-
- var contentTypeEnum = allContentTypeColl.getEnumerator();
- while (contentTypeEnum.moveNext()) {
- var currentCT = contentTypeEnum.get_current();
- if (currentCT.get_name() == contentTypeName) {
- CTypeID = currentCT.get_stringId();
- break;
- }
- }
- var testList = appCtxSite.get_web().get_lists().getByTitle("SampleList1");
-
- testList.set_contentTypesEnabled(true);
- testList.update();
- context.load(testList);
- var webContentTypes = appCtxSite.get_site().get_rootWeb().get_contentTypes();
- var listCollectionCT = testList.get_contentTypes();
- var customCT = webContentTypes.getById(CTypeID);
-
- listCollectionCT.addExistingContentType(customCT);
-
- context.load(listCollectionCT);
- var folder = testList.get_rootFolder();
- context.load(folder, 'ContentTypeOrder');
- context.executeQueryAsync(function () {
-
- folder.update();
- context.executeQueryAsync(
-
- function () {
- console.log("Content type was added");
-
- },
-
- function () {
- console.log("Error in Adding Content Type" + args.get_message());
-
- });
- }, function (sender, args) { onfail(sender, args); });
- }, function (sender, args) { onfail(sender, args); });
- }
-
-
- function onfail(sender, args) {
- alert('Failed to add content type in list. Error:' + args.get_message());
- }
-
-
- function manageQueryStringParameter(paramToRetrieve) {
- var params = document.URL.split("?")[1].split("&");
- var strParams = "";
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve) {
- return singleParam[1];
- }
- }
- }
Note - Please make sure to provide the permission to web in app manifest file
Finally custom content type will be added successfully on your existing list.
Summary
In this blog we have explored how to add the content type on existing SharePoint list form SharePoint hosted app model with JavaScript object model.