A sharepoint Person/Group column is a lookup field.

Updating a user to a custom person/group column,note the below points.

  • Sharepoint list columns have display names and internal names and one should refer to its Internal name in code
  • Every user has a unique sharepont id(a number) for a site collection and this id is needed to update user to person/group column

_spPagecontextinfo.userid  gives sharepoint id for current user.

Adding user to person or group column using REST

In the below example ‘Stakeholder’ is a custom person or group column and the column’s internal name is StakeholderId  and spID is the sharepoint id of the user

var spID =_spPagecontextinfo.userid;//to add current user

strUrl = “http://<site url>//_api/web/lists/getbytitle(‘ListName’)/items”;
strheader= {“Accept”: “application/json;odata=verbose”,
“X-RequestDigest”: $(“#__REQUESTDIGEST”).val()
};

var itemType = ‘SP.Data.ListNameListItem’;///ListItemEntityTypeFullName
var item = {
“__metadata”: { “type”: itemType },
         StakeholderId:spID
};
$.ajax({
url: strUrl,
type: “POST”,
async:false,
cache:false,
contentType: “application/json;odata=verbose”,
data: JSON.stringify(item),
headers:strHeader,
success: function (data){
///your code on success
},
error: function (error) {
//return alert(error.responseText);
}
});

To add a user other than the current user you need to pass the sharepoint id of that user and below function serves the purpose

Here’s where below EnsureUserFn function does the job.‘ensureuser’ method gets the sharepoint id of a existing user and generates the id for a new user.

However there may be other alternate ways

function EnsureUserFn(DomainIdofUser){
var spID;
$.ajax({
url:_spPageContextInfo.webAbsoluteUrl + “/_api/web/ensureuser“,
type: “POST”,
contentType: “application/json;odata=verbose”,
async:false,
data: JSON.stringify({ ‘logonName’: loginName}),
headers: {
“accept”: “application/json;odata=verbose”,
“X-RequestDigest”: $(“#__REQUESTDIGEST”).val()
},
success: function (data){                  

                       spID=data.d.Id;//for REST

spIDcsom=data.d.Id + “;#” + data.d.LoginName; //for CSOM
},
error: function (err){
alert(JSON.stringify(err));
}
});
return spID;///spIDcsom
}

Adding user to person or group column using Client Object Model

 var clientContext = new SP.ClientContext(“<<siteURl>>”);
var oList = clientContext.get_web().get_lists().getByTitle(‘Listname’);
var itemCreateInfo = new SP.ListItemCreationInformation();
oListItem = oList.addItem(itemCreateInfo);

oListItem.set_item(‘Stakeholder’, spIDcsom);

oListItem.update();
clientContext.executeQueryAsync(
Function.createDelegate(this, onCreateAscSucceeded),
Function.createDelegate(this, onCreateAscFailed)
);
function onCreateAscSucceeded() {
alert(“Success”);
}
function onCreateAscFailed(sender, args) { ////debugger;
return alert(“Error:”+args);
}

 

 

Advertisements