SharePoint Client Side People Picker using jQuery and Save Operation

In this post we will learn how to use Client Side People Picker Control and how to save its value to SharePoint List.

I have created Basic form which accept 3 parameters i.e. Username, Joining Date and Manager.

Note that here Client Side People Picker allows selection of multiple people and format of jQuery Datepicker control is dd/mm/yyyy.

Form:

List :
I just kept list name “Controls” for demo.
Also here default Title column is going to hold Username’s information.

Use below code to perform Add Operation using Form on List “Controls”

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <!-- Bootstrap Calendar, jQuery and CSS Link Start -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">      
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>      
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
      <!-- Bootstrap Calendar, jQuery and CSS Link End -->
      
      <!-- SharePoint Specific Javascript Start -->
      <script src="/_layouts/15/sp.runtime.js"></script>  
      <script src="/_layouts/15/sp.js"></script>  
      <script src="/_layouts/15/1033/strings.js"></script>  
      <script src="/_layouts/15/clienttemplates.js"></script>  
      <script src="/_layouts/15/clientforms.js"></script>  
      <script src="/_layouts/15/clientpeoplepicker.js"></script>  
      <script src="/_layouts/15/autofill.js"></script>  
      <script src="_layouts/15/sp.core.js"></script> 
      <!-- SharePoint Specific Javascript End -->

      <script>
         $(document).ready(function () {         
            /*** Initialize ClientSide People Picker ***/
            initializePeoplePicker('peoplepicker', true, 'People Only', 44);  
         
            /*** Initialize BootStrap Calendar ***/
             var date_input = $('input[name="date"]'); //our date input has the name "date"
             var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
             var options = {
                 format: 'dd/mm/yyyy',
                 container: container,
                 todayHighlight: true,
                 autoclose: true,
             };
             date_input.datepicker(options);


             $("#s4-ribbonrow").hide(); //hide the ribbon row
            $("#s4-workspace").children().hide(); //hide all elements in workspace
            var div = $("#ResponsiveDiv"); //move the div to make it visible
            $("#s4-workspace").append(div); //add the div after s4-workspace
         
            /*** Initialize ClientSide People Picker ***/
            function initializePeoplePicker(peoplePickerElementId, AllowMultipleValues, PeopleorGroup, GroupID) {  
            // Create a schema to store picker properties, and set the properties.  
                var schema = {};  
                schema['SearchPrincipalSource'] = 15;  
                schema['ResolvePrincipalSource'] = 15;  
                schema['MaximumEntitySuggestions'] = 50;  
                schema['Width'] = '280px';  
                schema['AllowMultipleValues'] = AllowMultipleValues;  
                if (PeopleorGroup == 'PeopleOnly') schema['PrincipalAccountType'] = 'User';  
                else schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
                if (GroupID > 0) {  
                    schema['SharePointGroupID'] = GroupID  
                }  
                // 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);  
            }  
         
         })
      </script>
   </head>
   <body>
      <div class="container" style="width:300px;margin-left:0px" id="ResponsiveDiv">
         <h2>Input Form</h2>
         <div class="form-group">
            <label for="usr">Name:</label>
            <input type="text"  class="form-control input-sm" placeholder="Enter Username" id="usr">
         </div>
         <div class="form-group">
            <!-- Date input -->
            <label class="control-label" for="date">Joining Date</label>
            <input class="form-control" id="date" name="date" placeholder="DD/MM/YYYY" type="text" />
         </div>
         <div class="form-group">
            <!-- Date input -->
            <label class="control-label" for="Manager">Manager</label>
            <div id='peoplepicker'  /></div>
         </div>
         <div class="form-group">
            <!-- Date input -->
            <label class="control-label" for="date"></label>
            <button type="button" class="btn btn-default" onclick="return Save()">Save</button>
         </div>         
      </div>
   </body>
</html>
<script>
   function Save() {
   
       alert("Save Event Starts");
       
       /*** SharePoint List Name  ***/
       var listName = "Controls";
   
       /*** SharePoint Simple Date Format from DD-MM-YYYY TO MM-DD-YYYY ***/
       var dtBirth =  DateFormat($("#date").val());
   
       alert("Updted Date Format " + dtBirth);
   
       var peoplePickerId = 'peoplepicker';
       var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerId + '_TopSpan'];
   
       //Get Selected UserInfo From PeoplePicker 
       var selectedUsers = peoplePicker.GetAllUserInfo();        
   
      /*************************************************************************************Get User Id **********************************************************/
      //After Selection of peoplePicker Use we will extract each user's email Id. By Using Email Id we will get each user's Userid i.e. Id
      //Once we receive id We are going to make an array of Id which will help us to pass user Id i.e. People Picker Column Value 

    
      var str ="";      
      var myObj;
      myObj = { "results":[ ]};

      for(var a=0;a<selectedUsers.length;a++)
      {
        /*Get UserEmail Id From  Selected Users in People Picket */
        var useremail  = selectedUsers[a].EntityData.Email;
    
        /*Get User Email Id in Comma Seperated String. This is for reference purpose only  */
        str += GetUserIDByEmail(useremail) + ",";
       
        /*Get User Id and ADD it into Arrasy so that we can pass this information in Perople Picker Value*/    
        myObj.results.push(GetUserIDByEmail(useremail));
      }
       
       /* Remove Last , (comma) sign from selected userid */
       var selectedPeoplePickerID = str.substring(0, str.length-1);

       alert("USERID "+ selectedPeoplePickerID);       

       /*************************************************************************************Get User Id **********************************************************/
   
       /* Pass Selected  User Id in JSON MagaerId Parameter*/
       var itemProperties = {
           'Title': $("#usr").val(),
           'JoiningDate':dtBirth,
           'ManagerId':myObj
       };
   
       /******************************  Create List Item With Given Paramters Start ****************************************************************************************/
       CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, itemProperties, function () {
           alert("New Item has been created successfully.");
       }, function () {
           alert("Ooops, an error occured. Please try again.");
       });
       /******************************  Create List Item With Given Paramters End****************************************************************************************/

        /******************************  Create List Item Function Start  ****************************************************************************************/
   
       function CreateListItemWithDetails(listName, webUrl, itemProperties, success, failure) {
           var itemType = GetItemTypeForListName(listName);
           itemProperties["__metadata"] = {
               "type": itemType
           };
           $.ajax({
               url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName +
                   "')/items",
               type: "POST",
               contentType: "application/json;odata=verbose",
               data: JSON.stringify(itemProperties),
               headers: {
                   "Accept": "application/json;odata=verbose",
                   "X-RequestDigest": $("#__REQUESTDIGEST").val()
               },
               success: function (data) {
                   success(data);
               },
               error: function (data) {
                   failure(data);
               }
           });
       }
       // Get List Item Type metadata
       function GetItemTypeForListName(name) {
           return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
       }

       /******************************  Create List Item Function End  ****************************************************************************************/
   
       /******************************  Simple Date Format Function to convert from DD-MM-YYYY TO MM-DD-YYYY Start *************************************************/
       function DateFormat(date) {
           var tmp = date.split('/');
           var date = tmp[1] + '/' + tmp[0] + '/' + tmp[2];
           return date;
       }    
       /******************************  Simple Date Format Function to convert from DD-MM-YYYY TO MM-DD-YYYY End *************************************************/
   
       /****************************** Get UserID  using Email Code Start ************************************** *************************************************/
        function GetUserIDByEmail(useremail) {
          var res ;
          $.ajax({
              url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/SiteUsers?$filter=Email%20eq%20%27" + useremail +"%27" ,   
              async: false,
              type: "GET",        
              headers: { "Accept": "application/json; odata=verbose" },
              success: function (data) {            
                        $("#sample").empty();  
                  for (var i = 0; i < data.d.results.length; i++)   
                  {  
                      var item = data.d.results[i];  
                      $("#sample").append(item.Id + "\t" + item.Title + "<br/>");  				
                      res=item.Id;			
                  }  			
                    return res;			
              },
              error: function (data) {
                  failure(data);
              }
              });
      
          return res;
        }
        /****************************** Get UserID  using Email Code End ************************************** *************************************************/
   
   
   }
</script>

After Implementation of Code we are able to perform Add Item Operation with Single and multiple Person using People Picker Control.

With Multiple Person/Manager:

List Item Value After Save Operation

One thought on “SharePoint Client Side People Picker using jQuery and Save Operation

  1. Thanks Nilesh. The code worked great 🙂

Leave a comment