Custom People Picker In SharePoint Online

Introduction 

For a SharePoint developer, creating custom forms to perform the CRUD operation on List items is a must-know task. During development, we may be stuck in some fields, such as giving ‘People Picker’ control over custom forms which shows the list of users from the Azure Active Directory of the SharePoint Tenant.

The reason behind this is that these fields have pre-defined column type in SharePoint, such as ‘Person or Group’ for OOTB People Picker column. We cannot simply put a text input box for this type of requirement.

Objective

Create a People Picker custom input field which will leverage the user profile information from SharePoint and Azure Active Directory using jQuery.

Process

  1. Create a Person or Group column in SharePoint list and select Yes/No for ‘Allow Multiple Selections’ as per your requirement.

    Custom People Picker In SharePoint Online
    Fig: Creating Person or Group column in SP site
    1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
    2. <script type="text/javascript" src="_layouts/15/clienttemplates.js"></script>  
    3. <script type="text/javascript" src="_layouts/15/clientforms.js"></script>  
    4. <script type="text/javascript" src="_layouts/15/clientpeoplepicker.js"></script>  
    5. <script type="text/javascript" src="_layouts/15/autofill.js"></script>  
  1. Include the following JavaScript references to your HTML file.
    1. <div>  
    2.     <label>User Name:</label>  
    3.     <div id="_UserName"></div>  
    4. </div>  
  1. Create a <div> element with ‘id’ attribute for People Picker field. We will initialize the <div> tag with People Picker field which will display an input field.

    Custom People Picker In SharePoint Online
    Fig: Initial view of the HTML form
  1. Now, let us move to the JavaScript code.
    1. $(document).ready(function() {  
    2.     initializePeoplePicker("_UserName");  
    3. });  
    4. function initializePeoplePicker(peoplePickerElementId) {  
    5.     var schema = {};  
    6.     schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
    7.     schema['SearchPrincipalSource'] = 15;  
    8.     schema['ResolvePrincipalSource'] = 15;  
    9.     schema['AllowMultipleValues'] = false;  
    10.     schema['MaximumEntitySuggestions'] = 50;  
    11.     schema['Width'] = '280px';  
    12.     this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);  
    13. }  
  2. Call a function on page load to initialize <div> tag with People Picker control.

    Fig: Code to initialize for Single selection People Picker
    1. $(document).ready(function() {  
    2.     initializePeoplePicker("_UserName");  
    3. });  
    4. function initializePeoplePicker(peoplePickerElementId) {  
    5.     var schema = {};  
    6.     schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
    7.     schema['SearchPrincipalSource'] = 15;  
    8.     schema['ResolvePrincipalSource'] = 15;  
    9.     schema['AllowMultipleValues'] = true;  
    10.     schema['MaximumEntitySuggestions'] = 50;  
    11.     schema['Width'] = '280px';  
    12.     this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);  
    13. }  
  1. If we need to initialize the People Picker with Multiple selection, we will have to make a slight change in the code to achieve that:

    Fig: Code to initialize Multiple selection People Picker
  1. After the initialization of People Picker, the HTML form control will change as shown below.

    Custom People Picker In SharePoint Online
    Fig: HTML form showing People Picker Input Field
  1. Now, the People Picker is initialized. Just type in the field, it will show the User Name from the Active Directory who has a SharePoint license assigned to their User Profile.

    Custom People Picker In SharePoint Online
    Fig: People Picker showing User Name from SharePoint Tenant
  1. As we have initialized this div for Single selection, it will automatically handle it if more than one name is entered.

    Custom People Picker In SharePoint Online
    Fig: Showing error when more than one name is entered
  1. Now that Initialization of People Picker is completed, let us see how to save the Name entered to the SharePoint List.
    1. function ensureUser() {  
    2. var peoplePickerTopDivId = $('#_UserName').children().children().attr('id');  
    3. var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerTopDivId];  
    4. var users = peoplePicker.GetAllUserInfo();  
    5. var arryuser = users[0];  
    6. if(arryuser) {  
    7.     var payload = { 'logonName': arryuser.Key};   
    8.     $.ajax({  
    9.         url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/ensureuser",  
    10.         type: "POST",  
    11.         async:false,  
    12.         contentType: "application/json;odata=verbose",  
    13.         data: JSON.stringify(payload),  
    14.         headers: {  
    15.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
    16.             "accept""application/json;odata=verbose"  
    17.         },  
    18.         success: function(data, status, xhr) {        
    19.            UserId = data.d.Id;            
    20.         },  
    21.         error: function(xhr, status, error) {      
    22.         }  
    23.     });   
    24.     }     
    25.     else {  
    26.         UserId = 0;  
    27.     }  
  2. Call a function on button click to get the User Properties using REST API.

    Fig: Code to get User Properties from SharePoint tenant
  1. In the above code, we are extracting User’s ID from SharePoint because the ‘Person or Group’ column saves the entries based on User ID and not the User Name or Email.

  2. Trigger a POST REST call on the submit event to save the User Name in the list.
    1. $.ajax({  
    2.         url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+listname+"')/items",  
    3.         type: "POST",  
    4.         async: false,  
    5.         data: JSON.stringify({  
    6.             __metadata: {  
    7.                 type: "SP.Data.PeopleListItem"  
    8.             },  
    9.             UserNameId: UserId  
    10.         }),  
    11.         headers: {    
    12.             "Accept""application/json;odata=verbose",    
    13.             "Content-Type""application/json;odata=verbose",    
    14.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),    
    15.             "X-HTTP-Method""POST",  
    16.         },  
    17.         success: function(data){  
    18.             alert("User Name is saved successfully");  
    19.         },  
    20.         error: function(error){  
    21.             alert(JSON.stringify(error));  
    22.        }  
    23.     });  
    fig: REST POST call to save User Name

NOTE
We have created a column ‘UserName’, but we are saving the details in ‘UserNameId’.

If your column name is ‘ColumnName’, the column name to save User Name by ID will need to use ‘ColumnNameId’. The  Id at the end of the column name will tell SharePoint to save the User ID.

As I said earlier, ‘Person or Group’ type columns only saves ID, not Name or Email using custom code.