Creating a List
In my previous post, I described how to add a list to SharePoint. In here, I'm going to describe how to add fields to an existing list. First, you need to refer to the same JavaScript files in your script page (SP.core.js, SP.runtime.js, SP.js).
There are a few approaches that you can use to add fields to the existing list. But in my personal opinion, I like the following approach because:
- It is easy rather that use XML to add entire field
- Intelligence are support based on field type (text, choice, user...)
- Code is more readable than XML
<script type="text/ecmascript">
function addFields() {
var clientContext = new SP.ClientContext.get_current();
var oWebsite = clientContext.get_web();
oList = clientContext.get_web().get_lists().getByTitle('CustomList');
var fldCollection = oList.get_fields();
var f1 = clientContext.castTo(
fldCollection.addFieldAsXml('<Field Type="Text"
DisplayName="NewField" Name="NewField" />', true,
SP.AddFieldOptions.addToDefaultContentType),
SP.FieldText);
f1.set_title("CurrentDate");
f1.set_description("sample desc");
f1.update();
var f2 = clientContext.castTo(
oList.get_fields().addFieldAsXml('<Field Type="Choice"
DisplayName="choice" Name="fldchoice" />', true,
SP.AddFieldOptions.addToDefaultContentType),
SP.FieldChoice);
var choices = Array("Approved", "Rejected", "Progress");
f2.set_choices(choices);
f2.update();
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
alert("List Field Updated");
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
In this example, I'm adding SharePoint Choice Field (SP.FieldChoice
) and SharePoint Text Field to existing SharePoint list.
Note: You can you addFieldAsXml
and can give complete XML as a string
to add the field as well.