Introduction
This article explains how to create a field in a list in SharePoint 2013 using CSOM-JavaScript.
Prerequisites
The following are the prerequisites:
- Ensure you have access to the Office 365 online.
- Ensure Napa tool is available in your site.
Procedure
The following is the procedure to be followed:
- Create an app for SharePoint using Office 365 Tools. If you have missed out on how to create an app in SharePoint 2013, then Click here
- Click on the App.js file.
- Globally declare the content, web and list objects as shown below.
var context = SP.ClientContext.get_current(); //gets the current context
var web = context.get_web(); //gets the web object
var list = web.get_lists(); //gets the collection of lists
- Now write the function to create a field in a list as in the following:
function createFieldInList() {
var targetList = list.getByTitle("MyCustomList");
field = targetList.get_fields().addFieldAsXml(
'<Field DisplayName=\'MyCustomField\' Type=\'Text\' />', true, SP.AddFieldOptions.defaultValue);
context.load(field);
context.executeQueryAsync(onFieldCreationSuccess, onFieldCreationFail);
}
- Here in this example we are creating a field in a list.
- “addFieldAsXML” is one of the methods to create a field.
- After creating the field object we need to load this object and then the code is executed by calling executeQueryAsync().
function onFieldCreationSuccess() {
alert("Success");
$('#message').text = "";
$('#message').text(field.get_title() + " got created");
}
// This function is executed if the above call fails
function onFieldCreationFail(sender, args) {
alert('Failed to create a field. Error:' + args.get_message());
}
- Now call the createFieldInList function inside the createList function.
function createList() {
listCreation = new SP.ListCreationInformation();
listCreation.set_title("MyCustomList"); //list title
listCreation.set_templateType(SP.ListTemplateType.genericList); //list type
list.add(listCreation)
context.load(list);
context.executeQueryAsync(onListCreationSuccess, onListCreationFail);
createFieldInList(); //after creating the list create the field.
}
Note: The list should be created before you create a field in the list. Click here if you want to know how to create a list in SharePoint 2013.
- The final snapshot of the enitre code is as in the following:
Testing
- Now to run the app click on the "Play" button that is available towards the left-most corner.
- The app is packaged, deployed, and installed on your Office 365 Site.
- Now you will be able to see the message “MyCustomField got created” in the page.
- To see the field that was recently created, just go to the following URL:
Syntax: https://yoursite/Lists/ListName
Example: https://mysite/Lists/MyCustomList
Summary
Thus in this article you saw how to create a field in a list in SharePoint 2013 using CSOM-JavaScript.