Question

I want to add a list element via JavaScript which works (almost).

After the help from a user here I got this

function fillStandard() {
    console.log("Standard");
    var posInvest =  "Invest"; 
    var posRecipient = accResponsible;
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Position');
    var item = new SP.ListItemCreationInformation();

    var oListItem = oList.addItem(item);
    oListItem.set_item('PosType', posInvest);
    oListItem.set_item('Recipient', posRecipient);

    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    console.log("successfully executed");
}

function onQueryFailed(sender, args) {
    console.log("failed");
    alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

If I outcomment oListItem.set_item('Recipient', posRecipient); it works.

The problem is that I have defined accResponsible as

var accResponsible = "[{\"email\":\"john.doe@blabla.net\",\"id\":\"i:0#.w|opmain\\\\eojdoe\",\"label\":\"John, Doe\",\"title\":\"\",\"type\":\"User\",\"value\":\"i:0#.w|opmain\\\\eojdoe\"}]";

which gives an error (invalid data has been used to update the field)

The field should normally get the value of a user (peoplePicker), for example something like this

posRecipient = NWF$("#" +varManager1).val(accResponsible);

But when I do that, the field remains blank. Does someone know how to solve this?

recipient

Was it helpful?

Solution

The problem is the value you have in this variable accResponsible. User field in SharePoint list cannot be update using a var value, we need a SP.FieldUserValue to put it into the list.

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

How to set any SP.Field Value with JSOM (Javascript) in Sharepoint 2013.

// 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);

For more information, refer the below links:

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

  2. Add multiple people using Javascript Client Object Model to a Field of Type SPFieldUserValue.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top