1

I'm using Javascript to update my fields in a SharePoint list via Rest requests.

I have several columns in my list representing different people (some multiple people columns, some single).

When updating a multiple-user type column, I have no problem passing back an array of the ID's I want in the array to update. If I want to remove all of the people, I simply post an empty array in the column and the field is essentially null.

This works well with an option list with multiple users:

//Note, this is inside a function that gives me the "ThisPhase", "ControlToUpdate" and "ThisColumn" objects.
var UsersSelected = [];  //this is the array we save back to sharepoint for the current column we're editing.
var UserNames = "";  // this is the text we save to the log
var UsersData = []; // this is the data we put back in the row for the redraw of the table

$('#CURRENT_USER_LIST option').each(function(){
    UsersSelected.push(parseInt($(this).val()));
    UserNames += $(this).text() + ", ";
    UsersData.push({
        Id: parseInt($(this).val()),
        Title: $(this).text()
    });
});

var ItemProperties = {};

ItemProperties[ThisColumn] = {
    'results': UsersSelected
};

if(UsersSelected.length > 0){
    //we have at least one user assigned
    ThisPhase[ThisColumn] = {
        "results": UsersSelected
    };
}
else{
    //nobody assigned
    ThisPhase[ThisColumn] = {
        "results": null
    };
};

updateListItem(_spPageContextInfo.webAbsoluteUrl,'PROJECT%20PHASES',ThisPhase.Id,ItemProperties,
    function(data){//successfully updated.
        if(UsersData.length > 0){
            UserNames = "";
            for (var c = 0; c < UsersData.length; c++) {
                UserNames += UsersData[c].Title + (UsersData.length > c+1 ? ", ": "");
            };
        };

        $(ControlToUpdate).html(UserNames);

    },logError);

The problem comes when I attempt to pass a null value back on a single user column. when I pass a null value into the "ThisColumn" (which is a single user column):

var UserSelected = 0;  //this is the array we save back to sharepoint.
var UserName = "";  // this is the text we save to the user log
var UsersData; // this is the data we put back in the row for the redraw of the table

UserSelected = $('#SINGLE_NEW_USER_LIST').val() || null;
UserName = UserSelected ? $('#SINGLE_NEW_USER_LIST :selected').text() : "";
UserData = {
    Title: UserName
};

var ItemProperties = {};
ItemProperties[ThisColumn] = UserSelected;

updateListItem(_spPageContextInfo.webAbsoluteUrl,'PROJECT%20PHASES',ThisPhase.Id,ItemProperties,
    function(data){ //successfully added information
        ThisPhase[ThisColumn] = UserSelected;

        UserName = UserSelected ? UserName : "[CLICK TO ADD "+ColumnToDisplayText+"]";

        $(ControlToUpdate).html(UserName);
    },
    function(err){
        console.log(err);
    }
);

I get the following error back from SharePoint :

"Cannot convert a primitive value to the expected type 'Edm.Int32'. See the inner exception for more details."

I've been searching for quite a while, but I can't seem to find any answers on how to use a POST request to REMOVE an ID from a Single-user field in SharePoint .

Any help would be much appreciated.

  • What does the updateListItem method look like? You might need to use a DELETE request instead of a POST request. – Thriggle Aug 23 '16 at 21:08
1

Make sure the user field value is specified as <FieldName>Id: null in request, for example:

url: <webUrl>/_api/web/lists/getbytitle('<listTitle>')/items(<itemId>)  
method: POST
headers:
      "X-HTTP-Method": "MERGE",
      "If-Match": "*"
body: {
       "__metadata": { "type": "SP.Data.TasksListItem" },
       "ApproverId": null
      }

where

ApproverId corresponds to single-user field named Assigned


Assume a Tasks list with single-user field named Assigned, then the following example demonstrates how to remove its value:

var listTitle = "Tasks";
var itemProperties = {
    '__metadata': { "type": "SP.Data.TasksListItem" },
    "AssignedToId": null
};
var itemId = 1;
var webUrl = _spPageContextInfo.webServerRelativeUrl;


updateListItem(webUrl,listTitle,itemId,itemProperties)
.done(function(item)
{
    console.log('List item has been updated');
})
.fail(function(error){
    console.log(JSON.stringify(error));
});

where

function executeJson(options) 
{
    var headers = options.headers || {};
    var method = options.method || "GET";
    headers["Accept"] = "application/json;odata=verbose";
    if(options.method == "POST") {
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
    }   

    var ajaxOptions = 
    {       
       url: options.url,   
       type: method,  
       contentType: "application/json;odata=verbose",
       headers: headers
    };
    if("data" in options) {
      ajaxOptions.data = JSON.stringify(options.data);
    }  

    return $.ajax(ajaxOptions);
}


function updateListItem(webUrl,listTitle,itemId,itemPayload)
{
     var options ={
        url: webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")",  
        method: "POST",
        headers : {
         "X-HTTP-Method": "MERGE",
          "If-Match": "*"
        },
        data: itemPayload    
     };     
     return executeJson(options);
}
  • Thanks for the comment. In my code, the variable [ThisColumn] is actually the column "AssignedToId". So I'm passing back thru: 'ItemProperties = { AssignedToId: null }' The Error SharePoint is returning back to me is saying it cannot convert the primitive value (null) to the expected ID which is type Int32. I think this should be correct. – Chris Bloom Aug 24 '16 at 13:30
1

I figured out the fix.

Rather than posting a null value to the id field, set the field to zero.

ItemProperties = {
    AssignedToId: 0
}

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.