0

How do I get the values of get_id() function into person/group field via REST? I know the syntax of the REST part has to be like:

'AssignedToId': {"results": [ID1, ID2,...]}

But how do I load the values into an array and pass this into {"results": []} ?

var Id = get_id();
'AssignedToId': {"results": [Id]} 

or

'AssignedToId': Id

doesn't work

EDIT: Here's the code

var hostweburl;
 var appweburl;
 var getId = new Array();

// Run your custom code when the DOM is ready.
$(document).ready(function () {


    initializePeoplePicker('peoplePickerDiv');


     //Get the decoded URLs
        hostweburl = GetUrlKeyValue("SPHostUrl");
        appweburl = GetUrlKeyValue("SPAppWebUrl");

        //resources are in URLs in the form:
        //web_url/layouts/15/resource
        var scriptbase = hostweburl + "/_layouts/15/";


        //load the js files and continue to the successHandler
        $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js",
                function () { $.getScript(scriptbase + "SP.RequestExecutor.js"); } 
            );
        }
    )

});

// Render and initialize the client-side People Picker.
function initializePeoplePicker(peoplePickerElementId) {

    // Create a schema to store picker properties, and set the properties.
    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);
}

// Query the picker for user information.
function getUserInfo() {

    // Get the people picker object from the page.
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    var userInfo = '';
    for (var i = 0; i < users.length; i++) {
        // Get the user's ID by using the login name.
        $.when(getUserId(users[i].Key))
        .then(function (result) {
                console.log(result.get_id());
                getId = result.get_id();
        });

    }

   // Get user keys.
   var keys = peoplePicker.GetAllUserKeys();

}

//Function to prepare and issue the request to get SharePoint Data
    function execCrossDomainRequest() {


       var rest_data = JSON.stringify({
            '__metadata': { 'type': 'SP.Data.TicketsListItem' },
            'Title': $("#Title").val(), 
            'AssignedToId': { 'results': getId}, 
            'Issue_x002d_Status': $("#status").val(), //be sure to enter the INTERNAL column name!
            'Priorit_x00e4_t': $("#prio").val(), //be sure to enter the INTERNAL column name!
            'Kategorie': $("#kat").val() 
        });


        //executor: The RequestExecutor object
        //Initialize the RequestExecutor with the add-in web URL
        var executor = new SP.RequestExecutor(appweburl);


        // Issue the call against the add-in web.
        // To get the title using REST we can hit the endpoint:
        // appweburl/_api/web/lists/getbytitle('listname')/items
        // The response formats the data in the JSON format.
        // The functions successHandler and errorHandler attend the sucess and error events respectively
        executor.executeAsync({
            url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists(guid'F1176C57-5AA4-4E73-9865-0EE5638FA682')/items?@target='" + hostweburl + "'", //use guid of list to make sure there are no errors
            method: "POST",
            body: rest_data,
            headers: {
                "Accept": "application/json; odata=verbose", "content-type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            },
            success: successHandler,
            error: errorHandler
        });

    }
    //Function to handle the success event.
    function successHandler() {

    }

    // Function to handle the error event
    function errorHandler() {

    }

// Get the user ID.
function getUserId(loginName) {

    var deferred = $.Deferred();

    var context = new SP.ClientContext.get_current();
    var user = context.get_web().ensureUser(loginName);
    context.load(user);
    context.executeQueryAsync(
         Function.createDelegate(null,
            function () { deferred.resolve(user); }),
        Function.createDelegate(null,
            function (sender, args) { deferred.reject(sender, args); }));

    return deferred.promise();
};

EDIT2:

$.when(getUserId(users[i].Key)).then(function (result) {
                getId.push(result.get_id().toString());
                alert(getId); 
            });

alert(getId);

the alert is showing me the correct Id's (from time to time in different order, but that shouldn't be a problem). Nevertheless there's nothing populated in my AssignedToId column. All the other columns getting filled.

var rest_data = JSON.stringify({
        '__metadata': { 'type': 'SP.Data.TicketsListItem' },
        'Title': $("#Title").val(),
        'AssignedToId': { "results": getId },
        'Issue_x002d_Status': $("#status").val(), //be sure to enter the INTERNAL column name!
        'Priority': $("#prio").val(), //be sure to enter the INTERNAL column name!
        'Category': $("#cat").val()
    });

    alert(rest_data);

the rest_data alert is giving me "...AssignedToId:{results: []}.."

EDIT3:

So I'm typing in 3 users and the alerts of alert(getId); are these

the alert of alert(rest_data); is this

3
  • Your question is not clear. Add more description Commented Sep 2, 2016 at 12:49
  • can please provide the alert ids what your are getting.
    – Sunil Sahu
    Commented Sep 8, 2016 at 11:21
  • edited the alerts
    – Jay T.
    Commented Sep 8, 2016 at 11:33

2 Answers 2

0

You can refer to the below code for updating multiple value in multiple people and group field:

var getId=get_id();
data: { "__metadata": { "type": "SP.Data.ListNameListItem" }, "AssignedToId": { "results": [getId,getId] } };

And for single value you can use:

data: { "__metadata": { "type": "SP.Data.ListNameListItem" }, "AssignedToId": { "results": [getId] } };
2
  • so as soon as I'm adding this code snippet to my rest call it doesn't execute the cross domain request. Though commenting the "AssignedToId" out, it creates the list item with all the other Information like status,..
    – Jay T.
    Commented Sep 5, 2016 at 8:38
  • Can you please post your rest call code it will be hekpfull
    – Sunil Sahu
    Commented Sep 6, 2016 at 6:13
0

Please update the code the below

var hostweburl;
var appweburl;
var getId = new Array();

$(document).ready(function () {


initializePeoplePicker('peoplePickerDiv');


 //Get the decoded URLs
    hostweburl = GetUrlKeyValue("SPHostUrl");
    appweburl = GetUrlKeyValue("SPAppWebUrl");

    //resources are in URLs in the form:
    //web_url/layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";


    //load the js files and continue to the successHandler
    $.getScript(scriptbase + "SP.Runtime.js",
    function () {
        $.getScript(scriptbase + "SP.js",
            function () { $.getScript(scriptbase + "SP.RequestExecutor.js"); } 
        );
    }
)

});

// Render and initialize the client-side People Picker.
function initializePeoplePicker(peoplePickerElementId) {

// Create a schema to store picker properties, and set the properties.
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 getUserInfo() {

// Get the people picker object from the page.
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
for (var i = 0; i < users.length; i++) {
    // Get the user's ID by using the login name.
    $.when(getUserId(users[i].Key))
    .then(function (result) {
            console.log(result.get_id());
            getId.push( (result.get_id()).toString());
    });

}

var keys = peoplePicker.GetAllUserKeys();

}

//Function to prepare and issue the request to get SharePoint Data
function execCrossDomainRequest() {

getUserInfo();
   var rest_data = JSON.stringify({
        '__metadata': { 'type': 'SP.Data.TicketsListItem' },
        'Title': $("#Title").val(), 
        'AssignedToId': { 'results': getId}, 
        'Issue_x002d_Status': $("#status").val(), //be sure to enter the INTERNAL column name!
        'Priorit_x00e4_t': $("#prio").val(), //be sure to enter the INTERNAL column name!
        'Kategorie': $("#kat").val() 
    });


    //executor: The RequestExecutor object
    //Initialize the RequestExecutor with the add-in web URL
    var executor = new SP.RequestExecutor(appweburl);


    // Issue the call against the add-in web.
    // To get the title using REST we can hit the endpoint:
    // appweburl/_api/web/lists/getbytitle('listname')/items
    // The response formats the data in the JSON format.
    // The functions successHandler and errorHandler attend the sucess and error events respectively
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists(guid'F1176C57-5AA4-4E73-9865-0EE5638FA682')/items?@target='" + hostweburl + "'", //use guid of list to make sure there are no errors
        method: "POST",
        body: rest_data,
        headers: {
            "Accept": "application/json; odata=verbose", "content-type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        },
        success: successHandler,
        error: errorHandler
    });

}
//Function to handle the success event.
function successHandler() {

}

// Function to handle the error event
function errorHandler() {

}

// Get the user ID.
function getUserId(loginName) {

var deferred = $.Deferred();

var context = new SP.ClientContext.get_current();
var user = context.get_web().ensureUser(loginName);
context.load(user);
context.executeQueryAsync(
     Function.createDelegate(null,
        function () { deferred.resolve(user); }),
    Function.createDelegate(null,
        function (sender, args) { deferred.reject(sender, args); }));

return deferred.promise();
};
5
  • Still get nothing populated in my list, the id's are only shown in the console log
    – Jay T.
    Commented Sep 6, 2016 at 9:25
  • It seems, that in line "getId = result.get_id();" nothing is committed to getId, still I'm wondering then why the correct Id's getting logged in the console
    – Jay T.
    Commented Sep 6, 2016 at 9:46
  • updated the code
    – Sunil Sahu
    Commented Sep 6, 2016 at 11:24
  • edited my code above
    – Jay T.
    Commented Sep 7, 2016 at 12:08
  • as I said above, right after the string is pushed to the getId-array the alert is showing me the correct Id's, but in my REST call the {"results": []} line is still empty, nothing is written in the assignedto column
    – Jay T.
    Commented Sep 8, 2016 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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