5

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.

4

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

4

According to the documentation:

MSDN

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.

4

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
});
  • I played with all the other solutions on this page and this is the only one I could make to work! Except I used this to get the username: var thisUserAccount = $().SPServices.SPGetCurrentUser({ fieldName: Name",debug: false }); because I have spservices hooked up. – bgmCoder Dec 3 '15 at 4:09
  • Oh! Sharepoint doesn't like this. You can use this method to set a username all right, but if I try to edit the box manually afterward, I get an This Page has been modified since you opened it. You must open the page again error. – bgmCoder Dec 4 '15 at 22:37
  • Here is my thread describing my problem: sharepoint.stackexchange.com/questions/164180/… – bgmCoder Dec 6 '15 at 1:56
  • That's why you don't modify it afterwards. Save/submit your form, then re-open. – vapcguy Dec 9 '15 at 17:59
  • oh sure, tell that to 600 users who barely know what they are doing in the first place. But you know, I can modify the username all day as long as I haven't tried to do it via javascript. I can manually change it and refresh it without saving to my heart's content. It's the script that messes it up - but I haven't yet figured out why. – bgmCoder Dec 9 '15 at 20:11
2

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();

});
  • Thanks Mike. I have managed to get the user name by userInfoList = web.get_siteUserInfoList(); camlQuery = new SP.CamlQuery(); camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/><Value Type=\'Number\'>' + _spUserId + '</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>'); – user13408 Jun 27 '14 at 13:09
  • So I think I will concentrate on your QuerySuccess method where you have set the value. – user13408 Jun 27 '14 at 13:11
0

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.

0

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);
            }
0
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy