I have a list with one Lookup field stores employees and one people picker, what am looking is based on a user login I want the user name to be default in the people picker and if the user name exists in the PP want it to be a default in to the lookup too, so when even user opens a new form they see their name on the two fields by default.
2 Answers
We can get the current username using REST API, then set the default value for lookup field and people picker field using the code below. Modify the field name in the code below and add code into a script editor web part into newform.aspx page.
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', SetDefaultValue);
});
function SetDefaultValue(){
var userName=GetCurrentUser();
var lookupFieldName="Employees";
var ppFieldName="People";
$("select[title='"+lookupFieldName+"'] option:contains('"+userName+"')").prop('selected','selected');
SetAndResolvePeoplePicker(ppFieldName,userName);
}
function GetCurrentUser() {
var userName="";
var userid=_spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
$.ajax({
url: requestUri,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
userName = data.d.Title;
},
error: function (data) {
}
});
return userName;
}
function SetAndResolvePeoplePicker(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);
}
</script>
You will need to add this logic to the NewForm.aspx. Most straightforward is to modify the NewForm.aspx with SharePoint Designer, and add reference to your new JavaScript file. In this new JavaScript file (that you can put e.g., in /_catalog/masterpage), you can use CSOM to query for user name and populate the people picker.
Populating people picker with JavaScript can be done with code like
function SetUserFieldValue(fieldName, userName) {
var _PeoplePicker = $("div[title='" + fieldName + "']"); //first people picker
var _PeoplePickerTopId = _PeoplePicker.attr('id');
var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
_PeoplePickerEditer.val(userName);
var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOject.AddUnresolvedUserFromEditor(true);
}