July 28, 2016

Client Side People Picker with JSOM in Office 365/SharePoint 2013

Requirement:
In one of the project, I had a requirement to use people picker in Client side HTML which should have same features as SharePoint OOTB people picker provides.

PeoplePicker.png

Approach/Solution:
Follow below steps to achieve client side people picker functionality using JSOM.

1. Below mentioned JS files are required to load client side people picker using JSOM. All
JS
files are OOTB SharePoint JS files which are available under "_layouts/15" folder in
SharePoint.
- clienttemplates.js
- clientforms.js
- clientpeoplepicker.js
- autofill.js
- sp.js
- sp.runtime.js
- sp.core.js
2. Put reference of all JS files into HTML file for which you want to create Client Side People
Picker.
3. Add below Div tag in your HTML file.
<div id="peoplePickerDiv"></div>
4. Add below code in your custom JS file (custompeoplepicker.js) and also put reference of this file into HTML file.
        // Initialize People Picker.   
 $(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';  
  //This value specifies where you would want to search for the valid values
  schema['SearchPrincipalSource'] = 15;             
  //This value specifies where you would want to resolve for the valid values
  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);  
                        }
                         // Get user information from client side people picker.
  // 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>';
}
}
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
// 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() {
console.log(this.user.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}

// Below code sets values into client side people picker.
var divPeople = SPClientPeoplePicker.SPClientPeoplePickerDict.PeoplePickerDiv_TopSpan;
PeoplePickerDiv_TopSpan - Specify the unique ID of the DOM element where the picker will render.
var userObj = { 'Key': "sample@sample.com" };
divPeople.AddUnresolvedUser(userObj, true);

If you have any questions you can reach out our SharePoint Consulting team here.

7 comments:

  1. Hi, I want to set Assigned to Column value from SharePoint list person column.. Can you help me in this

    ReplyDelete
  2. I got error when type the name in the input box
    Object doesn't support property or method 'set_formDigestHandlingEnabled'

    ReplyDelete
    Replies
    1. Hi Pradipta,

      Please check the order of scripts which are loaded on your page. It may prevent SharePoint from initializing all of the standard JavaScript on that page.

      Make sure that scripts are loaded as per below order.
      • jquery.min.js
      • sp.runtime.js
      • sp.js
      • strings.js
      • clienttemplates.js
      • clientforms.js
      • clientpeoplepicker.js
      • autofill.js
      • sp.core.js

      Let us know if issue still persists even after changing order of script.

      Delete
  3. Thank You for such a valuable post.
    Can you help me to set the values in client people picker.

    ReplyDelete
  4. Hi Prachi

    If you want to set the value in client people picker, You will need below things.

    --Client Side People Picker Id
    --Account Id or Email of User/group which you want to set in client side people picker

    Below is the code for set value in client side people picker

    var divPeople = SPClientPeoplePicker.SPClientPeoplePickerDict.PeoplePickerDiv_TopSpan;
    PeoplePickerDiv_TopSpan - Specify the unique ID of the DOM element where the picker will render.

    var userObj = { 'Key': "sample@sample.com" };

    divPeople.AddUnresolvedUser(userObj, true);

    ReplyDelete
  5. I got the below error
    Cannot read property 'AddUnresolvedUser' of undefined.

    ReplyDelete
    Replies
    1. Hi Harsh,

      Replace "PeoplePickerDiv" with unique Id of your people picker control in below code.

      var divPeople = SPClientPeoplePicker.SPClientPeoplePickerDict.PeoplePickerDiv_TopSpan;

      Hope it works for you.

      Delete