People Picker Get using sp.js & Update(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 and TestScript.js. Add the following code in the Scripts.js file
  • 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="/_layouts/15/clienttemplates.js" type="text/javascript"></script>

<script src="/_layouts/15/clientforms.js" type="text/javascript"></script> 

<script src="/_layouts/15/clientpeoplepicker.js" type="text/javascript"></script>

<script src="/_layouts/15/autofill.js" type="text/javascript"></script> 

<script src="/_layouts/15/sp.js" type="text/javascript"></script>

<script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>

<script src="/_layouts/15/sp.core.js" type="text/javascript"></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>
     </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 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 () {
    initializePeoplePicker('peoplePickerDiv');
});

//Auto Populate User and Group Field
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);
}

//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):

function fnCreateItem()
{
    getUserInfo();
}
// Render and initialize the 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();
      // 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() {
    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(1)",
        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));
        }
    });
    
 }

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