PeoplePicker get & Update List item 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 RestPeoplePicke.js
- Open any page & Insert content editor webpart. Include the below code in Content Editor.
//Code for content editor:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="/sites/<Site>/<Subsite>/SiteAssets/RestPeoplePicker.js"></script>
<input name="fname" id="txtUser" type="text">
<input onclick="GetValues()" type="button" value="Get UserID"/>
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 RestPeoplePicker.js:
//Below Function change the text box into people search box
//this function get the user details from current user id
$(document).ready(function()
{
$("#txtUser").autocomplete({
source: search,
minLength: 2
});
});
//Below function return the users names based on the values typed in the text box
function search(request,response) {
//var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
//var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var serverUrl = _spPageContextInfo.webAbsoluteUrl;
var restSource = serverUrl+ "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser";
// var principalType = this.element[0].getAttribute('principalType');
$.ajax(
{
'url':restSource,
'method':'POST',
'data':JSON.stringify({
'queryParams':{
'__metadata':{
'type':'SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters'
},
'AllowEmailAddresses':true,
'AllowMultipleEntities':false, //if we want this is a multiple people picker then set 'true'
'AllUrlZones':false,
'MaximumEntitySuggestions':50,
'PrincipalSource':15,
'PrincipalType': 15,
'QueryString':request.term
}
}),
'headers':{
'accept':'application/json;odata=verbose',
'content-type':'application/json;odata=verbose',
'X-RequestDigest':$("#__REQUESTDIGEST").val()
},
'success':function (data) {
var d = data;
var results = JSON.parse(data.d.ClientPeoplePickerSearchUser);
if (results.length > 0) {
response($.map(results, function (item) {
return {label:item.DisplayText,value:item.DisplayText}
//return {label:item.DisplayText,value:item.Key} //Here you can get multiple properties of users
}));
}
},
'error':function (err) {
alert("search:"+JSON.stringify(err));
}
});
}
//Below 3 functions will get the user ID based on the user name.
// in this function we will get user id & we can call the Add/Update Function
function GetValues()
{
var success = getDetailFromPPSearchUser($("#txtUser").val(),'Employee'); //here we are passing user displayname, source as any string( here 'Employee')
success.done(function(employeeresults){
$.map(employeeresults, function (employeeItem) {
//sp.js code to ensure user (this will insert user to site if not present)
var context = SP.ClientContext.get_current();
var theUser = context.get_web().ensureUser(employeeItem.Key);
context.load(theUser);
context.executeQueryAsync(function()
{
var successUserSelected = GetIDForTheSelectedUser(employeeItem.Key);
successUserSelected.done(function(UserId)
{
alert(UserId);
//Here we can call the function of ADD/Update
//addListItem('https://<SiteURL>','TestList',UserID)
});
},
function(sender, args){alert("GetValues : "+args.get_message());});
});
});
}
// this function to check the user name is in site or not
function getDetailFromPPSearchUser(inputString,source){
var deferred = $.Deferred();
var serverUrl = _spPageContextInfo.webAbsoluteUrl;
var restSource = serverUrl+ "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser";
$.ajax(
{
'url':restSource,
'method':'POST',
'data':JSON.stringify({
'queryParams':{
'__metadata':{
'type':'SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters'
},
'AllowEmailAddresses':true,
'AllowMultipleEntities':false,
'AllUrlZones':false,
'MaximumEntitySuggestions':50,
'PrincipalSource':15,
'PrincipalType': 15,
'QueryString':inputString
}
}),
'headers':{
'accept':'application/json;odata=verbose',
'content-type':'application/json;odata=verbose',
'X-RequestDigest':$("#__REQUESTDIGEST").val()
},
'success':function (data) {
//$('body').removeClass('loading');
var d = data;
var results = JSON.parse(data.d.ClientPeoplePickerSearchUser);
if (results.length == 1) {
deferred.resolve(results);
}
else
{
}
},
'error':function (err) {
$('#txtshellUser').unbind("click");
if(JSON.parse(err.responseText).error.code == "-2130575252, Microsoft.SharePoint.SPException")
{
alert("Security validation of the page expired. Please refresh the page.!")
}
else
{
alert(JSON.stringify(err));
}
deferred.reject();
}
}
);
return deferred.promise();
}
/// this function Getting the ID for the selected people picker
/// username should be passed as 'domain\username'
function GetIDForTheSelectedUser(userName) {
var deferred = $.Deferred();
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
/// make an ajax call to get the site user
$.ajax({
url: siteUrl + "/_api/web/siteusers(@v)?@v='" +
encodeURIComponent(userName) + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
//popup user id received from site users.
deferred.resolve(data.d.Id);
},
error: function (data) {
console.log(JSON.stringify(data));
alert(JSON.stringify(data));
deferred.reject();
}
});
return deferred.promise();
}
from the above code you can get user ID & call the Add/Update function
//Below code for ADD & Update list item (first we are getting the user id from the above function & call this function after getting the UserID):
// Get the user ID from Login name.
addListItem('https://<SiteURL>','TestList',<UserID>)
//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
.
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; //List Item ID which we are going to update
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));
}
});
}
Comments
Post a Comment