Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add user to sharepoint list item user field using REST api in sp2013?

I have a basic sharepoint list with people field in it, now I am trying to use rest api to add new list item and trying to set person field to my alias but it is not working and throwing me below error. looks like it is problem with how my user data is passed but I could not able to find any help online.

can you guys help with the correct way to make this call, any help is greatly appreciated.

my Code----------

function runAjax(){   var d  = JSON.stringify({"__metadata":{"type":"SP.Data.RepositoryItem"},"Owners":"-1;#[email protected]"});
jQuery.ajax({ 
    url: "https://microsoft.sharepoint.com/sites/mysite/docstore/_api/web/lists/GetByTitle('Repository')/items(1580) ",
    type: "POST", 
    headers: { 
        "accept": "application/json;odata=verbose", 
        "content-type": "application/json;odata=verbose", 
        "X-RequestDigest": $("#__REQUESTDIGEST").val(), 
        "X-HTTP-Method": "MERGE", 
        "If-Match": "*" 
    }, 
    data:d, 
    success: function (_a) { 
        console.log(JSON.stringify(_a)); 
    }, 
    error: function (_e) { 
        console.error(JSON.stringify(_e)); 
    } 
});}runAjax(); 

error I am getting is

Updation fail
{"readyState":4,"responseText":"{\"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.\"}}}","status":400,"statusText":"Bad Request"} 
like image 807
nbojja Avatar asked May 11 '13 17:05

nbojja


3 Answers

How to set User field value using SharePoint REST API

Assume the following function is used for creating a list item using SharePoint REST:

function createListItem(webUrl,listName,itemProperties) 
{    
    return $.ajax({       
       url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",   
       type: "POST",   
       processData: false,  
       contentType: "application/json;odata=verbose",
       data: JSON.stringify(itemProperties),
       headers: {   
          "Accept": "application/json;odata=verbose",
          "X-RequestDigest": $("#__REQUESTDIGEST").val()
       }  
    });
}

The format for user field value:

  • single-valued user field: '<user field name>' : <user id>
  • multi-valued user field: '<user field name>' : { 'results': [<array of user ids>] }

Multiple user field value

The example demonstrates how to create a task item and specify multi-valued AssignedTo field:

//Create a Task item
var taskProperties = {
    '__metadata' : { 'type': 'SP.Data.TasksListItem' },
    'Title': 'Order approval',
    'AssignedToId' : { 'results': [10] }
};
createListItem(_spPageContextInfo.webAbsoluteUrl,'Tasks',taskProperties)
.done(function(data)
{
   console.log('Task has been created successfully');
})
.fail(
function(error){
    console.log(JSON.stringify(error));
});

Single user field value

The example demonstrates how to create a task item and specify a single-valued AssignedTo field:

//Create a Task item
var taskProperties = {
    '__metadata' : { 'type': 'SP.Data.TasksListItem' },
    'Title': 'Order approval',
    'AssignedToId' : 10
};
createListItem(_spPageContextInfo.webAbsoluteUrl,'Tasks',taskProperties)
.done(function(data)
{
   console.log('Task has been created successfully');
})
.fail(
function(error){
    console.log(JSON.stringify(error));
});
like image 97
Vadim Gremyachev Avatar answered Sep 22 '22 12:09

Vadim Gremyachev


The error message you are receiving can be confusing. In this case, though the Person/Group field is named (display or internal name of the SharePoint list field) "Owners", when using REST API to update this field, it may be something else.

{"__metadata":{"type":"SP.Data.RepositoryItem"},"Owners":"-1;#[email protected]"}

To find out the exact field definition, try the following URL using GET method and investigate the XML value returned.

https://microsoft.sharepoint.com/sites/mysite/docstore/_api/web/lists/GetByTitle('Repository')/items(1580)

The XML may look something like the following

<m:properties> 
...
<d:DateModified m:type="Edm.DateTime">2014-01-07T00:00:00Z</d:DateModified><d:OwnersById m:null="true" />
...
</m:properties>

Most likely you will notice that the field "Owners" is named something else, such as "OwnersId". You will need to reconstruct your ajax post data to use the exact field name and specify the user's Id property instead of user's LoginName property as the posted value.

like image 42
sean Avatar answered Sep 23 '22 12:09

sean


The right way should be as shown below: (I am sure it will save someone sometime)

 var requestApprover = {
                        '__metadata' : { 'type': 'Collection(Edm.Int32)' },
                        'results': [10,20,30]
                    };

Remember the field name should contain Id at the end and the type should be the field type that you are updating where for people or groups (multiple) is Collection(Edm.Int32).

like image 36
M. Arnold Avatar answered Sep 23 '22 12:09

M. Arnold