Karine Bosch’s Blog

On SharePoint

Creating fields using CSOM in SharePoint 2013


Recently, I was working on a project where we wanted to create SharePoint fields using the .NET client object model (CSOM). You can easily find examples on the internet on how to create a text field, but we had a lot of trouble to find out how to create a calculated field.

Calculated fields can be created in a number of flavors. The following code snippet generates a calculated field that will show employee data as follows:

Karine Bosch (id 82176)

string formula = "<Formula>=FirstName&amp; \" \" &amp;LastName&amp; \" (id: \" &amp;EmployeeID&amp; \" \"</Formula>"
      + "<FieldRefs>"
      + "<FieldRef Name='FirstName' />"
      + "<FieldRef Name='LastName' />"
      + "<FieldRef Name='EmployeeID' />"
      + "</FieldRefs>";

string schemaCalculatedField = "<Field ID='<GUID>' Type='Calculated' Name='FullName' StaticName='FullName' 
   DisplayName='Full Name' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>" + formula + "</Field>";
Field fullNameField = demoList.Fields.AddFieldAsXml(schemaCalculatedField, true, AddFieldOptions.AddInternalNameHint);
clientContext.ExecuteQuery();

You can read more on how to create other type of fields using CSOM here.

Tip

To learn how to provision a calculated field, I created this type of field in a blank site through the UI of SharePoint. Then I saved the site as template. This saves the site as a .wsp and stores it in the Solution gallery. From there you can download it and import it in Visual Studio.

Import wsp

Once the .wsp imported, you will notice that all fields, content types, list instances and other elements that make up your site are translated into CAML and features:

Import wsp 2

Click on the elements.xml in the Fields folder to see the definition of all fields.

 

May 14, 2015 - Posted by | CSOM, SharePoint 2013

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: