Use
SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', function ()
{
var neededPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[GiveTheIndexHere];
var usrObj = { 'Key': 'i:0#.w|domain\user' };
neededPeoplePicker.AddUnresolvedUser(usrObj, true);
})
Adding my complete code below.
The requirement was to auto-populate L1, L2, L3 managers based on the user name added to the 'Process Owner' field.
$(document).ready(function()
{
SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', function ()
{
var processOwnerFieldIdProcessOwner = $("div[title='Process Owner']").attr('id');
SPClientPeoplePicker.SPClientPeoplePickerDict[processOwnerFieldIdProcessOwner].OnControlValidateClientScript = function (peoplePickerId, selectedUsersInfo)
{
console.log('inside OnValueChangedClientScript');
var processOwnerFieldUserInfoJson = SPClientPeoplePicker.SPClientPeoplePickerDict[processOwnerFieldIdProcessOwner].GetAllUserInfo();
if(processOwnerFieldUserInfoJson.length > 0 )
{
var processOwnerFieldUserId = processOwnerFieldUserInfoJson["0"].AutoFillKey;
processOwnerFieldUserId = encodeURIComponent(processOwnerFieldUserId);
console.log(processOwnerFieldUserId);
getManagersOfUser(processOwnerFieldUserId);
}
};
function getManagersOfUser(processOwnerFieldUserId)
{
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='"+processOwnerFieldUserId+"'",
method: "GET",
headers:
{
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function(data)
{
console.log(data);
populateL1L2L3Managers(data.d.ExtendedManagers.results);
},
error: function(error)
{
console.log(JSON.stringify(error));
}
})
}
function populateL1L2L3Managers(managersArray)
{
var counter = 1;
for(var i = managersArray.length-1; i> managersArray.length-4 && i >= 0;i--)
{
console.log(managersArray[i]);
//debugger;
var peoplePickerName;
if(counter == 1)
{
peoplePickerName = "L1_x0020_Manager";
}
else if(counter == 2)
{
peoplePickerName = "L2_x0020_Manager";
}
else if(counter == 3)
{
peoplePickerName = "L3_x0020_Manager";
}
counter++;
try
{
var travelPeoplePicker = null;
for (var prop in SPClientPeoplePicker.SPClientPeoplePickerDict)
{
if (prop.indexOf(peoplePickerName) >= 0)
{
travelPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[prop];
break;
}
}
if (travelPeoplePicker != null)
{
travelPeoplePicker.DeleteProcessedUser();
var usrObj = { 'Key': managersArray[i] };
travelPeoplePicker.AddUnresolvedUser(usrObj, true);
}
}
catch (e)
{
//alert(e);
}
}
}
});
});