SharePoint CSOM: How to update person or group field using ValidateUpdateListItem?

21.3k Views Asked by At

I am updating a SharePoint list item using the ValidateUpdateListItem method of the client-side object model to prevent creation of a new item version. This basically works fine for all fields except the ones with person or group field type. Does anyone know what is the correct string representation of a user or group value to be used as FieldValue of an ListItemFormUpdateValue object? I have already tried everything that seems reasonable to me (user ID from User Info, login name, lookup-value like combinations of these data etc.) without any success.

2

There are 2 best solutions below

3
On BEST ANSWER

Unfortunately ListItem.ValidateUpdateListItem method does not support the update of user field value. For example, in the following example AssignedTo field will not be updated:

using (var ctx = GetContext(webUri, userName, password))
{
     var list = ctx.Web.Lists.GetByTitle(listTitle);
     var item = list.GetItemById(itemId);

     var formValues = new List<ListItemFormUpdateValue>();
     formValues.Add(new ListItemFormUpdateValue() { FieldName = "Title", FieldValue = taskName});
     formValues.Add(new ListItemFormUpdateValue() { FieldName = "AssignedTo", FieldValue = userId.ToString() });  //not supported
     item.ValidateUpdateListItem(formValues, true, string.Empty);
     ctx.ExecuteQuery();

}

Instead consider ListItem.Update Method to update user field value as demonstrated below:

using (var ctx = GetContext(webUri, userName, password))       
{

      var list = ctx.Web.Lists.GetByTitle(listTitle); 
      var item = list.GetItemById(itemId);

      item["Title"] = taskName;
      var assignedToValue = new FieldUserValue() { LookupId = userId };
      var assignedToValues = new[] { assignedToValue };
      item["AssignedTo"] = assignedToValues;  //multi-valued user field
      item.Update();
      ctx.ExecuteQuery();
}
0
On

I just ran into a problem where updating more than 12 person or group fields with item update caused it to throw an exception. Apparently this is caused due to the list view look up threshold in SP online (12 as of this date).

http://blog.vanmeeuwen-online.nl/2012/07/value-does-not-fall-within-expected.html

To work around that I used the ValidateUpdateListItem method to update the person or group ids. The trick is to assign it a json in the format of

[{"Key":"i:0#.f|membership|[email protected]"}]

 formValues.Add(new ListItemFormUpdateValue() { FieldName = "AssignedTo", FieldValue = "[{'Key':'i:0#.f|membership|[email protected]'}]" });

For multiple values, it can be comma separated. Have not tried it with group but i think it should work.

Hopefully this can be useful for someone.