Add Column To Site Content Type in SharePoint using JSOM

The example in this topic show how to use JSOM to Add Column To Site Content Type in SharePoint

  • var oSiteContentTypes, clientContext, oSiteColumn;
  • function AddSiteColumnToContentType() {
  •     // You can optionally specify the Site URL here to get the context
  •     // If you don't specify the URL, the method will get the context of the current site
  •     // var clientContext = new SP.ClientContext("http://MyServer/sites/SiteCollection");
  •     clientContext = new SP.ClientContext();
  •  
  •     var oWeb = clientContext.get_web();
  •  
  •     // Get Site Column object
  •     oSiteColumn = oWeb.get_fields().getByInternalNameOrTitle('Column Name');
  •  
  •     // Get Site Content Type object
  •     oSiteContentTypes = oWeb.get_contentTypes();
  •  
  •     // Load Site Column to Client Context
  •     clientContext.load(oSiteColumn);
  •  
  •     // Load Site Content Type to Client Context
  •     clientContext.load(oSiteContentTypes);
  •  
  •     // Execute the query to the server.
  •     clientContext.executeQueryAsync(onQuerysuccess, onQueryfailed);
  • }
  •  
  • function onQuerysuccess() {
  •  
  •     // Iterate through Enumerator
  •     var oEnumerator = oSiteContentTypes.getEnumerator();
  •  
  •     var oContentType;
  •  
  •     // Counter variable to be used to break below loop
  •     var counter = 0;
  •  
  •     while (oEnumerator.moveNext())
  •     {
  •         // This line of codde is written to break the loop
  •         if (counter == 1)
  •         {
  •             break;
  •         }
  •  
  •         oContentType = oEnumerator.get_current();
  •  
  •         // Specify the Content Type Name here
  •         if (oContentType.get_name() == "Content Type Name") {
  •             counter += 1;
  •  
  •             var newSiteCol = new SP.FieldLinkCreationInformation();
  •             newSiteCol.set_field(oSiteColumn);
  •  
  •             //Add Site Column to ContentType
  •             oContentType.get_fieldLinks().add(newSiteCol);
  •  
  •             oContentType.update(true);
  •  
  •             //Load client context and execute batch
  •             clientContext.load(oContentType);
  •  
  •             clientContext.executeQueryAsync(onsuccess, onfailed);
  •         }
  •     }
  • }
  •  
  • function onQueryfailed(sender, args) {
  •     console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
  • }
  •  
  • function onsuccess() {
  •     console.log("success");
  • }
  •  
  • function onfailed(sender, args) {
  •     console.log('Creation Failed' + args.get_message() + '\n' + args.get_stackTrace());
  • }

Thank you for reading this article. This code was tested in SharePoint 2013

We value your feedback:

Page URL:

Name:

 

Email:

 
 

Feedback:

 

© 2019 Code SharePoint