5

I'm writing a user to a SharePoint list.

I've read that the SharePoint User field has a string like this inside of it: userId;#userLoginName

I've tried formatting in the same way when writing to a User field, for example when I write this string it works: 9;#i:0#.f|membership|ectropy@example.org

But what is strange (to me at least) is that 9;# seems to work or even 9. Even if I don't pass the userLoginName info at all, the loginId seems to be enough for it to recognize which User I'm talking about.

This seems to imply that when writing to the SharePoint User field, you only need the id, and the userLoginName, or, indeed, everything after the loginId is irrelevant.

Am I correct in my reasoning here? Or perhaps there's unexpected consequences if I leave off the userLoginName information?

Ectropy
  • 1,533
  • 4
  • 20
  • 37

2 Answers2

8

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());
    }
);
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 1
    Ok perfect, so rather than just doing `newItem.set_item('Manager', "9");` (which is how my current code works) it would be better to do `var assignedToVal = new SP.FieldUserValue(); assignedToVal.set_lookupId(9); item.set_item(fieldName,assignedToVal);` if I'm following correctly. – Ectropy Jun 18 '14 at 12:40
  • 1
    If user is of type SP.FieldUserValue then user.get_id() returns the UserId – Vadim Gremyachev Jun 18 '14 at 12:56
  • 1
    Do not forget to load the sp.js `SP.SOD.executeFunc('sp.js', 'SP.ClientContext', loadSPContext);` – Florian Leitgeb Jun 19 '15 at 13:30
0

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);
//
JCM
  • 51
  • 1
  • 1