I want to set current logged in user to people picker by javascript.
I can retrieve the value of user(lets say in var user).But how to set it to people control. Any help is much appreciated.
Use the following code:
<script type="text/javascript">
function SetPickerValue(pickerid, key, dispval)
{
var xml = '<Entities Append="False" Error="" Separator=";" MaxHeight="3">';
xml = xml + PreparePickerEntityXml(key, dispval);
xml = xml + '</Entities>';
EntityEditorCallback(xml, pickerid, true);
}
function PreparePickerEntityXml(key, dispval)
{
return '<Entity Key="' + key + '" DisplayText="' + dispval + '" IsResolved="True" Description="' + key + '"><MultipleMatches /></Entity>';
}
</script>
The easiest way to set PeopleEditor’s value is to use the EntityEditorCallbak function. This function is provided with built-in SharePoint javascript functions
Example of SetPickerValue call:
SetPickerValue('ctl00_PlaceHolderMain_pplEdit', 'domain\\m.kapusta','Marcin Kapusta');
Generated XML (for the given call) is the following:
<Entities Append="False" Error="" Separator=";" MaxHeight="3">
<Entity Key="domain\m.kapusta" DisplayText="Marcin Kapusta" IsResolved="True" Description="domain\m.kapusta">
<MultipleMatches />
</Entity>
</Entities>
http://digsharepoint.blogspot.in/2013/01/how-to-set-peopleeditor-value-using.html
According to the documentation:
Use this simple code to set value people picker:
//Get people picker Object
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict["peoplepickerID"]; // where peoplepickerID is ID of the element people picker that you could set value.
peoplePicker.AddUserKeys(user.DisplayText); // set value, where have user.DisplayText is the username in format: "LastName, FirstName", if have more one user then "Last, Name;Last2, Name2"
Sorry for my English.
Hope this helps.
SOLVED: None of these other answers above worked for me, and I don't know how they would. Here is my brute force method of how I got it to work using jQuery:
// Default the Requestor's Name
var welcomeText = $('[id*="zz8_Menu"]').text(); // this is zz7_Menu in SP 2007
var user = welcomeText.split('Welcome ')[1];
var counter=0;
$('div[title="People Picker"]').each(function() {
//alert(counter);
if (counter == 1) { // this is because I was setting the 2nd people picker on the page
$(this).html(user); // <-- this is the magic
}
counter++;
$('a[title="Check Names"]').click(); // <-- clicks the "Check Name" button programmatically to resolve your user
});
var thisUserAccount = $().SPServices.SPGetCurrentUser({ fieldName: Name",debug: false });
because I have spservices hooked up.
This Page has been modified since you opened it. You must open the page again
error.
I did this exact thing this week. Use a REST call and populate the people picker.
I used an excerpt from : http://lixuan0125.wordpress.com/2013/05/10/sharepoint-2013-get-current-user-loginname-using-jsom-rest/
$(document).ready(function () {
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
//removes the claims encoding
var loginName = data.d.LoginName.split('|')[1];
$("div[title='PeoplePickerColumnName']").val(loginName);
}
function QueryError(error) {
alert(error);
}
GetUserLogin();
});
SharePoint 2013 provides the SPClientPeoplePicker API to interface with the people picker.
http://ranaictiu-technicalblog.blogspot.kr/2014/11/sharepoint-2013-client-side-people.html
//Works with SharePoint 2010
$("div[title='People Picker']").text(strUserName);
//Works with SharePoint 2013
try {
//SharePoint 2013
var travelPeoplePicker = null;
for (var prop in SPClientPeoplePicker.SPClientPeoplePickerDict) {
if (prop.indexOf("YOUR_PEOPLEPICKER_FIELD_NAME_HERE") >= 0) {
travelPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[prop];
break;
}
}
if (travelPeoplePicker != null) {
var usrObj = { 'Key': strUserName };
travelPeoplePicker.AddUnresolvedUser(usrObj, true);
//$("input[title='TravelRequestor']").focus().val(strUserName).attr("size", strUserName.length);
}
}
catch (e) {
//alert(e);
}
If you are in infopath you can expand the field in the field list to see the display name node. Choose properties for display name. Then type the default display name exactly plus a semicolon, as it would appear when you actually select a person or group.
var usr;
var contextDR;
var webDR;
$(document).ready(function ()
{
initializePeoplePicker('peoplePickerteamleaderDiv');
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getusername);
});
//initialize PeoplePicker div tag
function initializePeoplePicker(peoplePickerElementId)
{
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '222px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}
//get plannedby user
function getusername()
{
contextDR = new SP.ClientContext.get_current();
webDR = contextDR.get_web();
usr = webDR.get_currentUser();
contextDR.load(usr);
contextDR.executeQueryAsync(Function.createDelegate(this, function () { usrsuccess(); }), Function.createDelegate(this, function () { usrfail(); }));
}
function usrsuccess(sender, args)
{
var a = usr.get_title() + ";";
var peoplePickerteamleaderDiv = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerteamleaderDiv_TopSpan;
peoplePickerteamleaderDiv.AddUserKeys(a);
}
function usrfail(sender, args)
{
}
body part:
<div id="peoplePickerteamleaderDiv"></div>
use this js reference:
_layouts/15/clienttemplates.js
_layouts/15/clientpeoplepicker.js
_layouts/15/clientforms.js
_layouts/15/autofill.js
_layouts/15/1033/strings.js