SharePoint 2013: Pre-Populate People Picker value to Current user

Save the following script in a .js file and upload it to Style Library or /_catalogs/masterpage.
Replace “FIELDNAME” with the field name you want to pre-populate.
Add a CEWP to the new form of the list/library.
Reference the js file.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>// <![CDATA[
$(document).ready(function () {
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : onSuccess,
  error : onError
});
}
function onSuccess(data, request){
 var userName= data.d.LoginName;
//parse the value. 
userName=userName.toString().split("i:0#.w|")[1];
 SetUserFieldValue("FIELDNAME",userName);
}
function onError(error) {
  //alert(error);
}
function SetUserFieldValue(fieldName, userName) {
 var _PeoplePicker = $("div[title='" + fieldName + "']");
 var _PeoplePickerTopId = _PeoplePicker.attr('id');
 var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
 _PeoplePickerEditer.val(userName);
 var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
 _PeoplePickerOject.AddUnresolvedUserFromEditor(true);
}
GetCurrentUser();
});
// ]]></script>

Leave a Reply