The proper way to write a SharePoint User to a User Field in a SharePoint list

痴心易碎 提交于 2019-12-04 08:58:55

Your assumption is correct, only User Id is a mandatory property when specifying value for a User field.

But since SP.FieldUserValue object is used to store value of User field, it is recommended to get and set values using this object as demonstrated in the below example:

var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
var list = lists.getByTitle(listTitle);
var item = list.getItemById(itemId);

var assignedToVal = new SP.FieldUserValue();
assignedToVal.set_lookupId(11);   //specify User Id 
item.set_item(fieldName,assignedToVal);
item.update();

ctx.executeQueryAsync(
    function() {
        console.log('Updated');
    },
    function(sender,args) {
        console.log('An error occurred:' + args.get_message());
    }
);

I find answer here using the person name instead the id is more easy than find user id if you dont have it.

https://gist.github.com/rheid/18635032d8371c7825b3320eae57071f

// Single Person  
   var singleUser = SP.FieldUserValue.fromUser('Peter Dotsenko');  
   oListItem.set_item('PetkaPersonSingle', singleUser);  

   //Multi Person  
   var petkaUserMultiArray = new Array("peterd@domain.com","Peter Dotsenko","domain\\peterd");  
   var lookups = [];  
   for (var ii in petkaUserMultiArray) {  
      var lookupValue = SP.FieldUserValue.fromUser(petkaUserMultiArray[ii]);  
      lookups.push(lookupValue);  
   }  
   oListItem.set_item('PetkaPersonMulti', lookups);
//
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!