Tuesday, October 28, 2014

How to change the number of decimal places on a number column using CSOM

Got a challenge for a one liner by the strongest man in SharePoint (@tarjeieo) to do this using CSOM as with with SSOM you can set the DisplayFormat property of the field. Using CSOM, this property is not available.

A one liner would be ugly, but the way to accomplish this is to modify the SchemaXml of the field, so you could encapsulate the code below in a function.

Using XML manipulation I ended up with this.

ClientContext clientContext = new ClientContext("https://site/);
Web web = clientContext.Web;
Field field = web.Fields.GetByTitle("DummyNum"); // Field to modify
clientContext.Load(field);
clientContext.ExecuteQuery();
XmlDocument doc = new XmlDocument();
doc.LoadXml(field.SchemaXml);
XmlNode fieldNode = doc.SelectSingleNode("Field");
XmlAttribute decimalAttribute = fieldNode.Attributes["Decimals"];
if (decimalAttribute == null)
{
decimalAttribute = doc.CreateAttribute("Decimals");
fieldNode.Attributes.Append(decimalAttribute);
}
decimalAttribute.Value = "4";
field.SchemaXml = doc.OuterXml;
field.UpdateAndPushChanges(true);
clientContext.ExecuteQuery();

No comments:

Post a Comment