People Picker getting user by sppeoplepicker.min.js & updating (Single & Multi User) using REST API IN SHAREPOINT 2013

Add a list item with People Picker (Single User & Multi User) Using REST API IN SHAREPOINT 2013


When you try to create/update list item just check the fields details of the list using the REST API. for an example I have created a List named TestList. Following is the field details:
  • Title: Text
  • TestColumn1: Text
  • TextColumn2: Text
  • TestColumn3: People and Group
Now to check the field details and check the details of the fields using the following REST API URL:

http://SITEURL/_vti_bin/client.svc/web/lists/getByTitle('TestList')/items
Now you will get following data in IE Or Chrome: 

Find your column name from the XML page. Now check the above picture carefully, the userid needs to be saved in the TestColumn3Id column not in the TestColumn3. Now check the following code:

  • Go To SiteAssets and & Add jquery-1.11.1.min.js , sppeoplepicker.min.js & TestScript.js. 
  • Open any page & Insert content editor webpart. Include the below code in Content Editor.

//Code for content editor:


<script src="/sites/<SiteName>/<SubsiteName>/SiteAssets/jquery-1.11.1.min.js" type="text/javascript"></script> 
<script src="/sites/<SiteName>/<SubsiteName>/SiteAssets/sppeoplePicker.min.js"></script>

<script src="/sites/<SiteName>/<SubsiteName>/SiteAssets/TestScript.js" type="text/javascript"></script> 

<table> 

   <tbody>
      <tr>
         <td>Title:</td>
         <td>
            <input id="txtTitle" type="text"/>
         </td>
      </tr> 
      <tr>
         <td>Test CL1:</td>
         <td>
            <input id="txtTestColumn1" type="text"/> 
         </td>
      </tr> 
      <tr>
         <td>Test CL2:</td>
         <td>
            <input id="txtTestColumn2" type="text"/>  
         </td>
      </tr> 
      <tr>
         <td>Test CL3:</td>
         <td>
            <div id="peoplePickerDiv"> </div>
         </td>
        <td><button id="pp1">Show</button></td>     </tr> 
     <tr>
         <td colspan="2">
            <input onclick="fnCreateItem()" type="button" value="Create Item"/>
         </td>
     </tr> 
   </tbody>
</table>


If you want to include any CSS files then include the below line
<link rel="stylesheet" type="text/css" href="/sites/<site>/<subsite>/SiteAssets/any.css"/>

Code For sppeoplepicker.min.js:

Please refer this link for more details about sppeoplepicker.min.js


(function (c) {
    function e(a) { var b = document.createElement("script"); b.setAttribute("type", "text/javascript"); b.setAttribute("src", "/_layouts/15/" + a); document.getElementsByTagName("head")[0].appendChild(b) } function f(a) { this.SPClientPeoplePicker_InitStandaloneControlWrapper(a, null, { PrincipalAccountType: "User,DL,SecGroup,SPGroup", SearchPrincipalSource: 15, ResolvePrincipalSource: 15, AllowMultipleValues: 0, MaximumEntitySuggestions: 50, Width: "260px" }) } function g(a) {
        a += "_TopSpan"; var b = null, c = this.SPClientPeoplePicker.SPClientPeoplePickerDict,
        d; for (d in c) if (d == a) { b = c[d]; break } if (null != b) { d = b.GetAllUserInfo(); a = ""; for (b = 0; b < d.length; b++) a += d[b].Key  + ";#"; return a } return ""
    } e("clienttemplates.js"); e("clientforms.js"); e("clientpeoplepicker.js"); e("autofill.js"); c.fn.spPeoplePicker = function () { var a = c(this).attr("id"); ExecuteOrDelayUntilScriptLoaded(function () { f(a) }, "sp.core.js") }; c.fn.getUserInfo = function () { var a = c(this).attr("id"); return g(a).slice(0, -2) }
})(jQuery);

from the above code you can get multiple propertied by changing the Key or  DisplayText or etc...

Also for multiple values you can change AllowMultipleValues: 1


Code For TestScript.js:

Below is the Code for people picker (This will load on page load & Change the html div control to people picker):

$(document).ready(function () {
     $(document).ready(function () {
                $("#peoplePickerDiv").spPeoplePicker();
             
            $("#pp1").click(function(){
                alert($("#peoplePickerDiv").getUserInfo());
                return false;
            });            
    });
});

//Below code will call the Button click event for ADD list item (first we are getting the user id from the selected people Picker & in the success event we are calling the update function):

// Get the user ID from Login name.
function fnCreateItem() {
    alert('loginName: '+$("#peoplePickerDiv").getUserInfo());
    var loginName = $("#peoplePickerDiv").getUserInfo();
    if(loginName.length != 0)
    {    
    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)
         );

    }

    else

    {alert('enter valid user name');}
}

function ensureUserSuccess() {
    addListItem('https://<SiteURL>','TestList',this.user.get_id());
}

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

//Code to Add new list item:

// Adding a list item with the metadata provided
function addListItem(url, listname,userid) {
    alert('UserID: '+userid);
    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": "SP.Data.TestListListItem"}
    }, {'Title': $('#txtTitle').val(),'TestColumn1': $('#txtTestColumn1').val(),'TestColumn2': $('#txtTestColumn2').val(),'TestColumn3Id': userid }); //If it is multi user field then instead of 'userid' we need to use -> {"results": [userid]} OR {"results": [userid1,userid2]}
    // Executing our add
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            alert('New item added');
        },
        error: function (data) {
            alert('FAILED');
        }
    });
}

Please refer this link for more details Link 1 Link 2
.

//Code to Update list item(With single user & Multiple user field):


function addListItem(url, listname,userid) {



alert('UserID: '+userid);

var itemID = 1;

    

                var item = $.extend({

                    "__metadata": { "type": "SP.Data.Workflow_x0020_TasksListItem"}

                  }, {'Title': $('#txtTitle').val(),'AssignedToId': {"results": [userid]}}); //Adding user to Multi user field, Here also we can give multi user like -> "results": [1,2]

    //}, {'Title': $('#txtTitle').val(),'TestUserId': userid });       //Adding user to single user to single user field

    

    $.ajax({

        url: url + "/_api/web/lists/getbytitle('" + listname + "')/getItemByStringId("+itemID +")",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        //data: Sys.Serialization.JavaScriptSerializer.serialize(item),
        headers: {
                    "Content-Type": "application/json;odata=verbose",
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),         
                    "X-Http-Method": "PATCH", //MERGE
                    "IF-MATCH": "*"
        },
        success: function (data) {
            alert('item Updated');
        },
        error: function (err) {
            alert("Failed: " + JSON.stringify(err));
        }
    });
    
 }


Please refer this link for more details sppeoplepicker.min.js

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

A type named 'SP.Data. could not be resolved by the model error

Add content type to SharePoint List/Library using REST API