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,
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,
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <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.
- 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.
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
-
-
- var oList = oWeb.get_lists().getByTitle('Test List');
- 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,
-
- var plainTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee Address" Name="EmployeeAddress" Required="False" NumLines="10" RichText="FALSE" AppendOnly="TRUE" />', true, SP.AddFieldOptions.addToDefaultContentType);
- plainTextField.set_description("This is a Plain multi line field");
- plainTextField.update();
-
-
- var richTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee History" Name="EmployeeHistory" Required="False" NumLines="12" RichText="TRUE" AppendOnly="TRUE" />', true, SP.AddFieldOptions.addToDefaultContentType);
- richTextField.set_description("This is a Rich Text multi line field");
- richTextField.update();
-
-
- 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);
- enhancedTextField.set_description("This is an Enhanced multi line field");
- enhancedTextField.update();
Output
Boolean, Image and Hyperlink Field
Boolean, Image and Hyperlink field is created using the below definition,
-
- var booleanField =fieldColl.addFieldAsXml('<Field Type="Boolean" DisplayName="Retired" Name="Retired" ><Default>0</Default></Field>', true, SP.AddFieldOptions.addToDefaultContentType);
- booleanField.set_description("This is a boolean field");
- booleanField.update();
-
-
- var imageField = fieldColl.addFieldAsXml('<Field Type="URL" DisplayName="Employee Image" Name="EmployeeImage" Required="False" Format="Image" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- imageField.set_description("This is an image field");
- imageField.update();
-
-
- var hyperLinkField = fieldColl.addFieldAsXml('<Field Type="URL" DisplayName="Employee Blog URL" Name="EmployeeBlogURL" Required="False" Format="Hyperlink" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- hyperLinkField.set_description("This is a hyperlink field");
- hyperLinkField.update();
Output
Number, Percentage and User Fields
Number, Percentage and User fields are created using the below definitions,
-
- var numberField = fieldColl.addFieldAsXml('<Field Type="Number" DisplayName="Age" Name="Age" Required="False" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- numberField.set_description("This is a number field");
- numberField.update();
-
-
- var percentageField = fieldColl.addFieldAsXml('<Field Type="Number" DisplayName="Training Completion" Name="TrainingCompletion" Percentage="TRUE" Required="False" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- percentageField.set_description("This is a percentage field");
- percentageField.update();
-
-
- var userField = fieldColl.addFieldAsXml('<Field Type="User" DisplayName="Manager" Name="Manager" Required="False" Format="Hyperlink" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- userField.set_description("This is an user field");
- userField.update();
Output
Lookup and Date Time fields
Look up and Date time fields are created using the below definitions,
-
- 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) ;
- lookupField.set_description("This is a lookup field");
- lookupField.update();
-
-
- var dateField = fieldColl.addFieldAsXml('<Field Type="DateTime" DisplayName="DOB" Name="DOB" Format="DateOnly" Required="False" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- dateField.set_description("This is a date field");
- dateField.update();
-
-
- var dateTimeField = fieldColl.addFieldAsXml('<Field Type="DateTime" DisplayName="Joining Date" Name="JoiningDate" Format="DateTime" Required="False" />', true, SP.AddFieldOptions.addToDefaultContentType) ;
- dateTimeField.set_description("This is a DateTime field");
- dateTimeField.update();
Output
Choice Fields
We can create Drop Down, Radio button and check box choice fields using the below definition,
-
- var choiceDropDownField = clientContext.castTo(
- oList.get_fields().addFieldAsXml('<Field Type="Choice" DisplayName="Expertise" Name="Expertise" Format="Dropdown" />', true, SP.AddFieldOptions.addToDefaultContentType),
- SP.FieldChoice);
- var availableDropChoices = Array("SharePoint", "jQuery", "SQL Server");
- choiceDropDownField.set_choices(availableDropChoices);
- choiceDropDownField.update();
-
-
- var choiceRadioButtonField = clientContext.castTo(
- oList.get_fields().addFieldAsXml('<Field Type="Choice" DisplayName="Experience" Name="Experience" Format="RadioButtons" />', true, SP.AddFieldOptions.addToDefaultContentType),
- SP.FieldChoice);
- var availableRadioChoices = Array("<5", "5-8", "8-12");
- choiceRadioButtonField.set_choices(availableRadioChoices);
- choiceRadioButtonField.update();
-
-
- var choiceCheckBoxField = clientContext.castTo(
- oList.get_fields().addFieldAsXml('<Field Type="MultiChoice" DisplayName="Preferred Location" Name="PreferredLocation" />', true, SP.AddFieldOptions.addToDefaultContentType),
- SP.FieldMultiChoice);
- var availableCheckBoxChoices = Array("London", "Kerala", "Dubai");
- choiceCheckBoxField.set_choices(availableCheckBoxChoices);
- choiceCheckBoxField.update();
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.
- 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.
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
-
- <script language="javascript" type="text/javascript">
- $(document).ready(function()
- {
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createFields);
- });
-
- var oListItem;
-
- function createFields()
- {
- debugger;
-
-
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
-
-
- var oList = oWeb.get_lists().getByTitle('Test List');
- var fieldColl = oList.get_fields();
-
-
- var plainTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee Address" Name="EmployeeAddress" Required="False" NumLines="10" RichText="FALSE" AppendOnly="TRUE" />', true, SP.AddFieldOptions.addToDefaultContentType);
- plainTextField.set_description("This is a Plain multi line field");
- plainTextField.update();
-
-
- var richTextField = fieldColl.addFieldAsXml('<Field Type="Note" DisplayName="Employee History" Name="EmployeeHistory" Required="False" NumLines="12" RichText="TRUE" AppendOnly="TRUE" />', true, SP.AddFieldOptions.addToDefaultContentType);
- richTextField.set_description("This is a Rich Text multi line field");
- richTextField.update();
-
-
- 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);
- enhancedTextField.set_description("This is an Enhanced multi line field");
- enhancedTextField.update();
-
-
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
-
- function QuerySuccess()
- {
- console.log("Fields created successfully.");
- }
-
- function QueryFailure(sender, args)
- {
- console.log('Request failed - ' + args.get_message());
- }
- </script>
- Go to the edit settings of the SharePoint page and click on Web part from the Insert tab,
- Add Content Editor Web part,
- Click on Edit Web art from Content Edit Web part. Assign the url of the script text file and click on Apply.
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.