How to prevent fill in values when saving over CSOM to a choice field

801 views Asked by At

I am writing some ETL code to move data between an external system and SharePoint Online.

I am using the nuget package Microsoft.SharePointOnline.CSOM to communicate with SP in C#.

I am using the following code to update my field values.

    spListItem[fieldName] = "Test Value";
    spListItem.Update();
    spClientContext.ExecuteQuery();

I noticed with Choice fields, if I save a non existing value SharePoint does not complain and just adds the value even if Allow 'Fill-in' choices is set to NO.

Is there a validate function anywhere in SharePoint? I saw some methods like ValidateUpdateListItem, but they didn't seem to do what I needed.

1

There are 1 answers

0
Vadim Gremyachev On BEST ANSWER

You could consider to validate choice field value before saving its value as demonstrated below:

static class ListItemExtensions
{

   public static bool TryValidateAndUpdateChoiceFieldValue(this ListItem item, string fieldName, string fieldValue)
   {
        var ctx = item.Context;
        var field = item.ParentList.Fields.GetByInternalNameOrTitle(fieldName);
        ctx.Load(field);
        ctx.ExecuteQuery();
        var choiceField = ctx.CastTo<FieldChoice>(field);
        if (!choiceField.FillInChoice)
        {
            var allowedValues = choiceField.Choices;
            if (!allowedValues.Contains(fieldValue))
            {
                return false;
            }
        }
        item.Update();
        return true;
    }
}

In that case the ListItem will be updated once the validation is succeeded.

Usage

 using (var ctx = new ClientContext(webUri))
 {
      var list = ctx.Web.Lists.GetByTitle(listTitle);
      var listItem = list.GetItemById(itemId);

      if(listItem.TryValidateAndUpdateChoiceFieldValue(fieldName,fieldValue))
        ctx.ExecuteQuery();

 }