0

I have created people picker on client side using SPpeoplepicker.js.

$("#peoplePickerDiv").spPeoplePicker();

Everything works perfect all user display in people picker and i can select multiple user in it. Now i want to get ID of selected user from people picker.

I got reference from MSDN. But it looks like complex. I would wants to change in SPPeoplePicker js to bind USER ID with Login name.

3 Answers 3

4

According to your requirement, you can not get the id from the ClientPeoplePicker Control, the walk around is quite simple, with the key data mentioned by @Akshay Randive, you can call the next function:

function GetUserId(userName) {
    //userName format = i:0#.w|bidev\sp_admin
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;

    var call = $.ajax({
        url: siteUrl + "/_api/web/siteusers(@v)?@v='" + 
                encodeURIComponent(userName) + "'",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" }
    });
    return call;
}

To call the method you use:

var getRevisor = GetUserId(keys);
getRevisor.done(function(user) {
    //user.d.Id <-- This is your precious data
});

With this you get the user ID

Greetings :)

4
  • You could also use a rest endpoint similar to the following one: http://[website]/_api/web/siteusers?$filter=substringof('|[AD domain][username]',LoginName) eq true
    – Alberto S.
    Commented Dec 20, 2017 at 17:13
  • 1
    The siteusers webmethod not always work. Sometimes the request user will not be found in that site (event though he has access ). A better solution is to use the ensureUser webmethod.
    – Alberto S.
    Commented Dec 21, 2017 at 11:30
  • 1
    if the peoplepicker find the user you dont not need to ensure it. and the web/siteusers endpoint will always find the user
    – Marco
    Commented Dec 21, 2017 at 13:39
  • not really. It depends in how you implement the peoplepicker. I am adding that functionality with just the ClientPeoplePickerWebServiceInterface and the user selected not always is found when running the web/siteusers REST query. That is why I recomend using the web/ensureUser method instead.
    – Alberto S.
    Commented Dec 21, 2017 at 14:41
1
$(document).ready(function () {

    // Specify the unique ID of the DOM element where the
    // picker will render.
    initializePeoplePicker('peoplePickerDiv');
});

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

    // Render and initialize the picker. 
    // Pass the ID of the DOM element that contains the picker, an array of initial
    // PickerEntity objects to set the picker value, and a schema that defines
    // picker properties.
    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++) {
        var user = users[i];
        for (var userProperty in user) { 
            userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
        }
    }
    $('#resolvedUsers').html(userInfo);

    // Get user keys.
    var keys = peoplePicker.GetAllUserKeys();
    $('#userKeys').html(keys);

    // Get the first user's ID by using the login name.
    getUserId(users[0].Key);
}

// Get the user ID.
function getUserId(loginName) {
    var context = new SP.ClientContext.get_current();
    this.user = context.get_web().ensureUser(loginName);
    context.load(this.user);
    context.executeQueryAsync(
         Function.createDelegate(null, ensureUserSuccess), 
         Function.createDelegate(null, onFail)
    );
}

function ensureUserSuccess() {
    $('#userId').html(this.user.get_id());
}

function onFail(sender, args) {
    alert('Query failed. Error: ' + args.get_message());
}

Here is complete solution Check here for more details

4
  • This return key of user like i:0#.w|bidev\sp_admin. I want User ID of user instead of key. Commented Jul 7, 2015 at 12:01
  • i have edited the above solution check it Commented Jul 7, 2015 at 12:32
  • 1
    I also got reference from MSDN. It work fine but if i select multiple user in people picker then i have to loop through each user and get ID for each. I have make code for it but it return only single value coz function is Async executeQueryAsync. So i got only last user's ID. I need to get all user's ID. So now question is that how to get all user's ID if i have select multiple users from People Picker? Commented Jul 7, 2015 at 12:37
  • What is get_id() in ensureUserSucess ? Commented Dec 28, 2018 at 7:43
1

I have use SPPeoplePicker which is easy to use and to save user in list item i can get ID of user directly from this JS like

$("#PeoplePickerDiv").getUserIDs()

It will return array of ID of all user from people picker and also work with multiple people picker. So i can directly save user in column.

3
  • getUserIDs() is not in the file. Commented Oct 17, 2017 at 3:04
  • 1
    github.com/KaushalKhamar/SPPeoplePicker Try this one with good documentations Commented Oct 30, 2017 at 6:51
  • I am getting this error: The HTTP method 'GET' cannot be used to access the resource 'EnsureUser'. The operation type of the resource is specified as 'Default'. Please use correct HTTP method to invoke the resource.
    – entryton
    Commented May 13, 2020 at 9: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.