Add Site Columns To Site Content Type On Host Web Using JSOM

Implementation

In my previous two articles you saw, how to:

  1. Create Site Columns On Host Web From App Web Using JavaScript In SharePoint 2013.
  2. Create Site Content Type In SharePoint 2013 using JSOM.

So, if you open the created Content type, you only see ‘Name’ and ‘Title’ fields there, which are basically added from Parent Content Types, now we will see how to add Site Columns to this Site Content Type present on Host Web from App Web.

 Content Types

We will perform following operations to achieve this:

  1. Get Host Web Context using App Web.
  2. Fetch already created Site Columns.
  3. Get the required Content Type from Host Web Content Type collection.
  4. Add Site Columns to this Content Type and update the Content Type.

Get Started:

  • Add a button on page to ‘Add Columns to Content Type’.
    1. <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>  
    2. <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">  
    3.    <div>  
    4.       <input type="button" id="btnAddColumns" value="Add Columns to Content Type" onclick="addColumnsToContentType()"/>  
    5.    </div>  
    6. </asp:Content>  
  • Update App.js and add the following code.
    1. 'use strict';  
    2. var context = SP.ClientContext.get_current();  
    3. var hostWebUrl, hostWebContext;  
    4. // This code runs when the DOM is ready and creates a context object which is   
    5. // needed to use the SharePoint object model  
    6. $(document).ready(function() {  
    7.     hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));  
    8.     hostWebContext = new SP.AppContextSite(context, hostWebUrl);  
    9. });  
    10. // Retrieve a query string value  
    11. function getQueryStringParameter(paramToRetrieve) {  
    12.     var params = document.URL.split("?")[1].split("&");  
    13.     for (var i = 0; i < params.length; i = i + 1) {  
    14.         var singleParam = params[i].split("=");  
    15.         if (singleParam[0] == paramToRetrieve) return singleParam[1];  
    16.     }  
    17. }  
    18. //Add Site Columns to Content Type  
    19. var hostWebContentTypes;  
    20. var contentTypeName = 'Employee'// Name of the Content Type where Colums will be added  
    21. var columnsInternalName = ["EmployeeId""EmployeeName"]; //Internal Names of the Site Columns  
    22. var createdColumns = new Array();  
    23.   
    24. function addColumnsToContentType() {  
    25.     var hostWeb = hostWebContext.get_web();  
    26.     //Get the columns that need to be added to Content type and store the objects in an Array.  
    27.     for (var iCreatedFieldsCounter = 0; iCreatedFieldsCounter < columnsInternalName.length; iCreatedFieldsCounter++) {  
    28.         createdColumns[iCreatedFieldsCounter] = hostWeb.get_fields().getByInternalNameOrTitle(columnsInternalName[iCreatedFieldsCounter]);  
    29.         context.load(createdColumns[iCreatedFieldsCounter]);  
    30.     }  
    31.     //Get Host Web Content type Collection  
    32.     hostWebContentTypes = hostWeb.get_contentTypes();  
    33.     context.load(hostWebContentTypes);  
    34.     context.executeQueryAsync(  
    35.         function() {  
    36.             //Call function to add columns to Content Type  
    37.             addColumns(contentTypeName, columnsInternalName, createdColumns);  
    38.         },  
    39.         function onItemsRefetchedFail(sender, args) {  
    40.             alert('Failed to fetch columns and Content Type. Error:' + args.get_message() + '\n' + args.get_stackTrace());  
    41.         });  
    42. }  
    43. // Add columns  
    44. function addColumns(ctypeName, fieldsInternalName, createdFields) {  
    45.     //Find the Content Type and then add Fields to it  
    46.     var createdContentType;  
    47.     var contentTypeEnumerator = hostWebContentTypes.getEnumerator();  
    48.     while (contentTypeEnumerator.moveNext()) {  
    49.         var contentType = contentTypeEnumerator.get_current();  
    50.         if (contentType.get_name() === ctypeName) {  
    51.             createdContentType = contentType;  
    52.             var fieldRef = new Array();  
    53.             for (var iAddFieldsCounter = 0; iAddFieldsCounter < createdFields.length; iAddFieldsCounter++) {  
    54.                 fieldRef[iAddFieldsCounter] = new SP.FieldLinkCreationInformation();  
    55.                 fieldRef[iAddFieldsCounter].set_field(createdFields[iAddFieldsCounter]);  
    56.                 createdContentType.get_fieldLinks().add(fieldRef[iAddFieldsCounter]);  
    57.                 createdContentType.update(true);  
    58.             }  
    59.             context.load(createdContentType);  
    60.             context.executeQueryAsync(onAddFieldToContentTypeSuccess, onAddFieldToContentTypeFail);  
    61.         }  
    62.     }  
    63. }  
    64.   
    65. function onAddFieldToContentTypeSuccess() {  
    66.     alert('Site Columns added to Content Type.');  
    67. }  
    68.   
    69. function onAddFieldToContentTypeFail(sender, args) {  
    70.     alert('Failed to add Site Columns to Content Type. Error:' + args.get_message() + '\n' + args.get_stackTrace());  
    71. }  
    72. //End  
  • Build and Deploy the solution and click ‘Add Columns to Content Type’ button. Site Columns will be added to Content Type.

    Add Columns to Content Type

  • Navigate to Host Web Site Content Type and you can see the newly added columns there.

    newly added columns

Conclusion

Using this JSOM approach, you can add Site Columns to Content type on Host Web from App Web. You can use this approach to add columns to App web Content Type too.