Before having Nintex forms, I came across a code that would populate a People field on a newly created form with the current user's Manager name.
In my case, it was needed that the user see's their manager's name on the form just to make sure that what they are submitting is going to the right person for approval, or, if their manager is away on vacation, the user can select a different manager for approval.
Here's the code.... to use it, edit the new form (DispForm.aspx), edit the page and add a Script Editor web part at the very bottom of the form.
This works for SharePoint Online, so I'm sure it will work on SharePoint 2013 as well.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var userid = _spPageContextInfo.userId;
function GetCurrentUser() {
//var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties/";
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 loginName = data.d.Title;
console.log(data);
var loginName = data.d.DisplayName;
var myManager = data.d.UserProfileProperties.results[15].Value;
//Use the following code to find Manager if results[15] is not Manager in future SharePoint
//var myManager = '';
//var x = data.d.UserProfileProperties.results;
//for (var i = 0; i < x.length; i++) {
// if (x[i].Key == 'Manager') {
// myManager = x[i].Value;
// break;
// }
//}
SetUserFieldValue("Employee Name",loginName);
SetUserFieldValue("Approval Manager",myManager);
}
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>
by Suolon via Everyone's Blog Posts - SharePoint Community
No comments:
Post a Comment