Karine Bosch’s Blog

On SharePoint

Creating fields using CSOM in SharePoint 2013


Recently I had a reader who asked how to to configure a calculated default value like “=YEAR([Today])”. This is not possible within one field as you cannot use [Today] or [Now] within the formula of a calculated field. The only way to solve this is to create 2 columns:

  • A DateTime field with default value Today. You can set this to hidden if you don’t want your users to see it.
  • A calculated field that outputs the year of your DateTime field.

Here is the code snippet:

private static void CreateCalculatedFieldBasedOnToday(ClientContext context)
{
     Web web = context.Web;
     List list = web.Lists.GetByTitle("CSOMFields");
     context.Load(list);
     context.ExecuteQuery();

     // Create a DateTime field that yields to Today
     string schemaTodaysDate = "<Field ID='{297B3AA2-85AD-408D-8346-0B64721C8090}' Type='DateTime' Name='TodaysDate' StaticName='TodaysDate' DisplayName='TodaysDate' Format='DateOnly' Hidden='FALSE' >"
           + "<Default>[Today]</Default></Field>";
     Field todaysDateField = list.Fields.AddFieldAsXml(schemaTodaysDate, true, AddFieldOptions.AddFieldInternalNameHint);
     context.ExecuteQuery();

     // Create a Calculated field that displays the Year of the Today field
     string formula = "<Formula>=YEAR(TodaysDate)</Formula>";
     string schemaCalculatedField = "<Field ID='{446A6933-1751-474D-A407-9EE0250C708B}' Type='Calculated' Name='TodaysYear' StaticName='TodaysYear' DisplayName='Todays Year' ResultType='Number' Decimals='0' Required='TRUE' ReadOnly='TRUE'>" + formula + "</Field>";
     Field calculatedField = list.Fields.AddFieldAsXml(schemaCalculatedField, true, AddFieldOptions.AddFieldInternalNameHint);
     context.ExecuteQuery();
}

Update: Steve Moucheron sent me his code snippet in which he solves in one go:

string fieldXml = "<Field DisplayName='Year' Type='Text'>"
   + "<DefaultFormula>=CONCATENATE(YEAR(Today))</DefaultFormula>"
   + "</Field>";
Field field = list.Fields.AddFieldAsXml(fieldXml, true, 
    AddFieldOptions.defaultValue);
context.ExecuteQuery();

Read more on creating fields using CSOM.

Advertisements

January 13, 2017 - Posted by | CSOM, SharePoint Online

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: