Exploring SharePoint Field Creation Using JavaScript Object Model in SharePoint 2016 And Office 365

The basic building blocks of SharePoint are list and libraries. There is a very subtle difference between the two when it comes to their purpose. Both are used to store and retrieve contents. Both lists and libraries can contain list items and documents respectively as their storage type. Each of the list items and documents can have multiple fields which will store metadata about the item. SharePoint Field defines the Site Column element. We can have multiple data types associated with the SharePoint fields as defined below,

create

In this article we will see how we can create each one of them. Each of them requires the setting of a certain set of parameters while defining the field element.

  • Add reference to jquery file,
    1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    2. <script language="javascript" type="text/javascript">  
  • Within Document ready function call SP.SOD.executeFunc so as to load the on demand script SP.js . Call the main starting point function, say: createFields.
    1. SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createFields);  
  • Instantiate client context and get the list instance. Once the list object is retrieved, get the field collection object. 
    1. var clientContext = new SP.ClientContext();    
    2. var oWeb = clientContext.get_web();    
    3.     
    4. //Get List and Field Collection object    
    5. var oList = oWeb.get_lists().getByTitle('Test List');    
    6. var fieldColl = oList.get_fields();    
  • Let’s see how we can instantiate different field types using JavaScript Object model :

    Text Fields

    We can create three different types of text fields – Plain Text field, Rich text field, Enhance text field using the definition shown below,
    1. //Add Plain Text field to the Field Collection    
    2. var plainTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee Address" Name="EmployeeAddress" Required="False" NumLines="10" RichText="FALSE" AppendOnly="TRUE" />'true, SP.AddFieldOptions.addToDefaultContentType);    
    3. plainTextField.set_description("This is a Plain multi line field");    
    4. plainTextField.update();    
    5.     
    6. //Add Rich Text field to the Field Collection    
    7. var richTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee History" Name="EmployeeHistory" Required="False" NumLines="12" RichText="TRUE" AppendOnly="TRUE" />'true, SP.AddFieldOptions.addToDefaultContentType);    
    8. richTextField.set_description("This is a Rich Text multi line field");    
    9. richTextField.update();    
    10.     
    11. //Add Enhanced Text field to the Field Collection    
    12. var enhancedTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee Skillset" Name="EmployeeSkillSet" Required="FALSE" NumLines="8" RestrictedMode="TRUE" RichText="TRUE" RichTextMode="FullHtml" AppendOnly="TRUE" />'true, SP.AddFieldOptions.addToDefaultContentType);    
    13. enhancedTextField.set_description("This is an Enhanced multi line field");    
    14. enhancedTextField.update();    
    Output

    Output

    Boolean, Image and Hyperlink Field

    Boolean, Image and Hyperlink field is created using the below definition,
    1. //Add Boolean field to the Field Collection    
    2. var booleanField =fieldColl.addFieldAsXml('<Field Type="Boolean" DisplayName="Retired" Name="Retired" ><Default>0</Default></Field>'true, SP.AddFieldOptions.addToDefaultContentType);    
    3. booleanField.set_description("This is a boolean field");    
    4. booleanField.update();      
    5.     
    6. //Add Image Field to the field Collection     
    7. var imageField = fieldColl.addFieldAsXml('<Field Type="URL" DisplayName="Employee Image" Name="EmployeeImage" Required="False" Format="Image" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    8. imageField.set_description("This is an image field");    
    9. imageField.update();    
    10.     
    11. //Add URL Field to the field Collection     
    12. var hyperLinkField = fieldColl.addFieldAsXml('<Field Type="URL" DisplayName="Employee Blog URL" Name="EmployeeBlogURL" Required="False" Format="Hyperlink" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    13. hyperLinkField.set_description("This is a hyperlink field");    
    14. hyperLinkField.update();    
    Output

    Output

    Number, Percentage and User Fields

    Number, Percentage and User fields are created using the below definitions,
    1. //Add Number field to the Field Collection    
    2. var numberField = fieldColl.addFieldAsXml('<Field Type="Number" DisplayName="Age" Name="Age" Required="False" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    3. numberField.set_description("This is a number field");    
    4. numberField.update();    
    5.     
    6. //Add Percentage field to the Field Collection    
    7. var percentageField = fieldColl.addFieldAsXml('<Field Type="Number" DisplayName="Training Completion" Name="TrainingCompletion" Percentage="TRUE" Required="False" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    8. percentageField.set_description("This is a percentage field");    
    9. percentageField.update();    
    10.     
    11. //Add User Field to the collection    
    12. var userField = fieldColl.addFieldAsXml('<Field Type="User" DisplayName="Manager" Name="Manager" Required="False" Format="Hyperlink" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    13. userField.set_description("This is an user field");    
    14. userField.update();    
    Output

    Output

    Lookup and Date Time fields

    Look up and Date time fields are created using the below definitions,
    1. //Add Look up field to the Field Collection    
    2. var lookupField = fieldColl.addFieldAsXml('<Field Type="Lookup" DisplayName="Employee Department" Name="EmpDepartment" Required="False" List="{E1B92017-0001-475E-A978-2275B12F3FDA}" ShowField="Department" RelationshipDeleteBehavior="None" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    3. lookupField.set_description("This is a lookup field");    
    4. lookupField.update();    
    5.     
    6. //Add Date Only field to the Field Collection    
    7. var dateField = fieldColl.addFieldAsXml('<Field Type="DateTime" DisplayName="DOB" Name="DOB" Format="DateOnly" Required="False" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    8. dateField.set_description("This is a date field");    
    9. dateField.update();    
    10.     
    11. //Add Date Time field to the Field Collection    
    12. var dateTimeField = fieldColl.addFieldAsXml('<Field Type="DateTime" DisplayName="Joining Date" Name="JoiningDate" Format="DateTime" Required="False" />'true, SP.AddFieldOptions.addToDefaultContentType) ;    
    13. dateTimeField.set_description("This is a DateTime field");    
    14. dateTimeField.update();    
    Output

    Output

    Choice Fields

    We can create Drop Down, Radio button and check box choice fields using the below definition,
    1. //Add Choice DropDown field to the Field Collection    
    2. var choiceDropDownField = clientContext.castTo(    
    3. oList.get_fields().addFieldAsXml('<Field Type="Choice" DisplayName="Expertise" Name="Expertise" Format="Dropdown" />'true, SP.AddFieldOptions.addToDefaultContentType),    
    4. SP.FieldChoice);    
    5. var availableDropChoices = Array("SharePoint""jQuery""SQL Server");    
    6. choiceDropDownField.set_choices(availableDropChoices);    
    7. choiceDropDownField.update();    
    8.     
    9. //Add Choice Radio Button field to the Field Collection    
    10. var choiceRadioButtonField = clientContext.castTo(    
    11. oList.get_fields().addFieldAsXml('<Field Type="Choice" DisplayName="Experience" Name="Experience" Format="RadioButtons" />'true, SP.AddFieldOptions.addToDefaultContentType),    
    12. SP.FieldChoice);    
    13. var availableRadioChoices = Array("<5""5-8""8-12");    
    14. choiceRadioButtonField.set_choices(availableRadioChoices);    
    15. choiceRadioButtonField.update();    
    16.     
    17. //Add Choice CheckBox field to the Field Collection    
    18. var choiceCheckBoxField = clientContext.castTo(    
    19. oList.get_fields().addFieldAsXml('<Field Type="MultiChoice" DisplayName="Preferred Location" Name="PreferredLocation" />'true, SP.AddFieldOptions.addToDefaultContentType),    
    20. SP.FieldMultiChoice);    
    21. var availableCheckBoxChoices = Array("London""Kerala""Dubai");    
    22. choiceCheckBoxField.set_choices(availableCheckBoxChoices);    
    23. choiceCheckBoxField.update();  
    Output

    Output

  • Execute the batch which will send the request to the server and perform the entire javascript object model operations as a batch. Loading of Client Context is not necessary during the creation of SharePoint fields.
    1. clientContext.executeQueryAsync(QuerySuccess,QueryFailure);  
    We can test this in SharePoint by adding it to the Content Editor web part as below,

  • Save the below code to a text file and save it into one of the SharePoint Libraries say, Site Assets.

    As an example, below code shows only the creation of different types of text fields.
    1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>    
    2.     
    3. <script language="javascript" type="text/javascript">    
    4.     $(document).ready(function()    
    5.     {    
    6.         SP.SOD.executeFunc('sp.js''SP.ClientContext', createFields);    
    7.     });    
    8.     
    9.     var oListItem;    
    10.     
    11.     function createFields()    
    12.     {    
    13.         debugger;    
    14.     
    15.         //Get Client Context and Web object    
    16.         var clientContext = new SP.ClientContext();    
    17.         var oWeb = clientContext.get_web();    
    18.     
    19.         //Get List and Field Collection object    
    20.         var oList = oWeb.get_lists().getByTitle('Test List');    
    21.         var fieldColl = oList.get_fields();    
    22.     
    23.         //Add Plain Text field to the Field Collection    
    24.         var plainTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee Address" Name="EmployeeAddress" Required="False" NumLines="10" RichText="FALSE" AppendOnly="TRUE" />'true, SP.AddFieldOptions.addToDefaultContentType);    
    25.         plainTextField.set_description("This is a Plain multi line field");    
    26.         plainTextField.update();    
    27.     
    28.         //Add Rich Text field to the Field Collection    
    29.         var richTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee History" Name="EmployeeHistory" Required="False" NumLines="12" RichText="TRUE" AppendOnly="TRUE" />'true, SP.AddFieldOptions.addToDefaultContentType);    
    30.         richTextField.set_description("This is a Rich Text multi line field");    
    31.         richTextField.update();    
    32.     
    33.         //Add Enhanced Text field to the Field Collection    
    34.         var enhancedTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee Skillset" Name="EmployeeSkillSet" Required="FALSE" NumLines="8" RestrictedMode="TRUE" RichText="TRUE" RichTextMode="FullHtml" AppendOnly="TRUE" />'true, SP.AddFieldOptions.addToDefaultContentType);    
    35.         enhancedTextField.set_description("This is an Enhanced multi line field");    
    36.         enhancedTextField.update();    
    37.     
    38.         //Execute batch . Loading the client context is not necessary.    
    39.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);    
    40.     }    
    41.     
    42.     function QuerySuccess()    
    43.     {    
    44.         console.log("Fields created successfully.");    
    45.     }    
    46.     
    47.     function QueryFailure(sender, args)    
    48.     {    
    49.         console.log('Request failed - ' + args.get_message());    
    50.     }    
    51. </script>   
  • Go to the edit settings of the SharePoint page and click on Web part from the Insert tab,

    Insert

  • Add Content Editor Web part,

    Web part

  • Click on Edit Web art from Content Edit Web part. Assign the url of the script text file and click on Apply.

    Content Edit

Click on Apply. This will create the fields in the SharePoint list which we can verify by going to the List settings. Thus we have seen how to create the different types of fields available within SharePoint using JavaScript object model.

Up Next
    Ebook Download
    View all
    Learn
    View all