Get the Current User's Manager in JavaScript
Using the JavaScript Object Model to look up the manager of the current user (from the User Profile Service) seems to be a fairly common requirement - I've had to do it at least three times in the last couple of months.
First of all, you need to load the profile properties for the current user:
var context, userProperties;
var stage1 = function() {
context = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(context);
userProperties = peopleManager.getMyProperties();
First of all, you need to load the profile properties for the current user:
var context, userProperties;
var stage1 = function() {
context = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(context);
userProperties = peopleManager.getMyProperties();
context.load(userProperties);
context.executeQueryAsync(stage2, onQueryFail);
}
Then you can retrieve the value of the Manager property as follows:
var stage2 = function() {
var manager =
context.executeQueryAsync(stage2, onQueryFail);
}
Then you can retrieve the value of the Manager property as follows:
var stage2 = function() {
var manager =
userProperties.get_userProfileProperties()["Manager"];
}
And that's it. Easy once you know how.
Incidentally, the trickiest part of all this can be getting the SharePoint script files to load in the right order. You can't run your code until sp.userprofiles.js is loaded, and you can't load sp.userprofiles.js until sp.js is loaded. The sp.userprofiles.js library seems to be particularly awkward to load. I usually use the following pattern, cobbled together from various helpful forum posts:
$(document).ready(function () {
// Force sp.js to load, then call sharePointReady
function sharePointReady() {
// Force sp.userprofiles.js to load, then call our custom code
if (!SP.SOD.executeOrDelayUntilScriptLoaded(stage1,
}
And that's it. Easy once you know how.
Incidentally, the trickiest part of all this can be getting the SharePoint script files to load in the right order. You can't run your code until sp.userprofiles.js is loaded, and you can't load sp.userprofiles.js until sp.js is loaded. The sp.userprofiles.js library seems to be particularly awkward to load. I usually use the following pattern, cobbled together from various helpful forum posts:
$(document).ready(function () {
// Force sp.js to load, then call sharePointReady
if (!SP.SOD.executeOrDelayUntilScriptLoaded(sharePointReady,
'sp.js')) {
LoadSodByKey('sp.js');
}
});}
function sharePointReady() {
// Force sp.userprofiles.js to load, then call our custom code
if (!SP.SOD.executeOrDelayUntilScriptLoaded(stage1,
'sp.userprofiles.js')) {
LoadSodByKey('userprofile');
}
}
}
}
Comments
Post a comment