0

I inherited a custom application from another developer who used REST API to create list items. Now the requirement is to add a multiple users people picker to the form.

I am able to add a multiple people picker to the form. However when I am trying to save I get this error "A node of type 'startArray' was read from the JSON reader when trying to read a value of property; however, a 'PrimitiveValue' or 'StartObeject' node was expected"

I understood from other blogs that the syntax should be "RequestorId": { "results": [106,111] }. But my problem in my code is to have this value in a variable and then push into an array and pass it into the function which does the creation of an item. What I am struggling here is the syntax for that variable.

Should I include the curly brackets as well {}

var    colsAndValues = [];  
var   peoplepicker1 = SPClientPeoplePicker.SPClientPeoplePickerDict.elvlglENotification_TopSpan;
                             if (peoplepicker1 != null) {
                      var users = peoplepicker1.GetAllUserInfo();
                        if (users.length == 0) {
                       //alert("No users");
                    //    Mutiple User/Lookup value format:   {FieldName: {"results": [LookupIdVal1,LookupIdVal2] }}

                        colsAndValues.push("RequestorId");
                        var UserValue =  "'results'"+":[0]";// Not sure if this is right syntax. Here is where I feel my problem is

                        colsAndValues.push(UserValue);
                    }

//Function for creating the list item

var item = {
                    "__metadata": { "type": itemType }
                };
                for(var i = 0; i < colsAndValues.length; i++) {
                    if (i % 2 !== 0) {

                        item[colsAndValues[i-1]] = colsAndValues[i];
                    }
                }
                var siteurl = _spPageContextInfo.webAbsoluteUrl;

                jQuery.ajax({
                    url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items",
                    type: "POST",
                    contentType: "application/json;odata=verbose",
                    data: JSON.stringify(item),
                    headers: {
                        "Accept": "application/json;odata=verbose",
                        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
                    },

2

We can use the REST API to get UserId of all the users in the people picker field, then pass field data as below to add item using REST API.

"RequestorId": { "results": userIds}

The following example code for your reference.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
<script type="text/javascript" src="_layouts/15/clienttemplates.js"></script>  
<script type="text/javascript" src="_layouts/15/clientforms.js"></script>  
<script type="text/javascript" src="_layouts/15/clientpeoplepicker.js"></script>  
<script type="text/javascript" src="_layouts/15/autofill.js"></script>

<div>
    <label>User Name:</label>  
    <div id="elvlglENotification"></div>
    <div><input type="button" value="Save" onclick="addToList()"></input></div> 
</div>
<script type="text/javascript">
$(document).ready(function() {  
    initializePeoplePicker("elvlglENotification");  
});  
function initializePeoplePicker(peoplePickerElementId) {  
    var schema = {};  
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
    schema['SearchPrincipalSource'] = 15;  
    schema['ResolvePrincipalSource'] = 15;  
    schema['AllowMultipleValues'] = true;  
    schema['MaximumEntitySuggestions'] = 50;  
    schema['Width'] = '280px';  
    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);  
}
function addToList(){
    var userIds=[];
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.elvlglENotification_TopSpan;
    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    for (var i = 0; i < users.length; i++) {
        var accountName=users[i].Key;
        var userId=GetUserId(accountName);
        if(userId!=-1){
          userIds.push(userId);
        }           
    }
    var listName="CL0801";
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "RequestorId": { "results": userIds}
    };  
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            alert('Success');           
        },
        error: function (data) {
            alert("Error");
        }
    });
}
function GetUserId(accountName){
    var userId=-1;
    /// get the site url
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    /// make an ajax call to get the site user
    $.ajax({
        url: siteUrl + "/_api/web/siteusers(@v)?@v='" +encodeURIComponent(accountName) + "'",
        method: "GET",
        async:false,
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            userId=data.d.Id;
        },
        error: function (data) {
            console.log(JSON.stringify(data));
        }
    });
    return userId;
}
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}  
</script>
  • Thank you for taking the time to write the code for me. However my error still remains the same when I am assigning the whole array for the multiple people picker field as below. "elvlglENotificationId": {"results":userIds} the request body shows this value ``` elvlglENotificationId":{"results":[{"$1T_1":-1}] I am not sure what I am doing wrong.. – user57156 Aug 4 at 5:07
  • You Id return "-1" mean, you can't find the user in the site using REST API. – LZ_MSFT Aug 5 at 1:22
  • ahhh.. I see.. That makes sense. Thank you. – user57156 Aug 5 at 17:04
  • I am able to create the items using the REST API code you have given above. Now when I am editing the item, I want to load the multiple people picker field values in my field, I have the following function to get by ID. How can I extract the vaues in my "elvlglENotification" field. jQuery.ajax({ url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + listID + "), method: "GET", headers: { "Accept": "application/json;odata=verbose" }, – user57156 Aug 5 at 17:05
  • var userIDs = data.d[elvlglEnotificationID]; is not giving the right result. – user57156 Aug 5 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.