Tuesday, January 12, 2016

User, Person or Group Fields with REST in SharePoint 2013

Setting the value of a user field in SharePoint 2013 using REST is straight-forward once you know how to reference the field.

Let's say you have a list named Work Requests with a Person or Group column named AssignedTo. Normally, to add or update an item you construct a JSON object with all the field/value pairs similar to:

{
  "__metadata": {
      "type": "SP.Data.WorkRequestsItem"
  },
  "Title": "Important Work Needed",
  "Description": "This is very important work.",
  "AssignedTo": 1
}

You stringify the object and send the request with $.ajax, but receive a 400 Bad Request response from SharePoint. Huh?

{
  "error": {
    "code": "-1, Microsoft.SharePoint.Client.InvalidClientQueryException",
    "message": {
      "lang": "en-US",
      "value": "A 'PrimitiveValue' node with non-null value was found when trying to read the value of
           a navigation property; however, a 'StartArray' node, a 'StartObject' node, or a
           'PrimitiveValue' node with null value was expected."
    }
  }
}

Next, you try all the various combinations of possible user values, but keep receiving an error.

  • "domain\username"
  • { "results": [ 1 ] }
  • "1;#user@domain.com"
  • "i:0#.w|domain\username"

THE SOLUTION is to add "Id" to the end of the field name and use the numeric ID of the user. So, the AssignedTo field becomes AssignedToId. You can verify the field names by requesting a specific item from the list. Try http://<site>/_api/web/lists/getbytitle('Work Requests')/items(2) in a browser to see the actual field names - where items(2) is the ID of an actual list item.

"AssignedToId": 1

That's it. The same technique is also used for lookup fields.

3 comments:

  1. Saved a ton of time!! Thank you very much

    ReplyDelete
  2. WOW! I have been looking for this for about 3 hours!. thanks!

    ReplyDelete