Capturing the Current User’s Manager in MOSS Using SPServices and GetUserProfileByName
I had a question today about how to get the current user’s manager and put the value into a Person or Group column in a list. This one only works in MOSS or SharePoint Server 2010 (not WSS 3.0 or SharePoint Foundation) because the UserProfileService Web Service is only available there.
The code is relatively straightforward: a call to SPServices to get the results from GetUserProfileByName and then a little more code to poke it into the appropriate Person or Group column. In this case, the Person or Group column is called ‘Manager’.
$(document).ready(function() { var managerName; $().SPServices({ operation: "GetUserProfileByName", async: false, AccountName: $().SPServices.SPGetCurrentUser(), completefunc: function (xData, Status) { $(xData.responseXML).find("PropertyData > Name:contains('Manager')").each(function() { managerName = $(this).parent().find("Values").text(); }); } }); // There's no easy way to find one of these columns; we'll look for the comment with the columnName var searchText = RegExp("FieldName=\"Manager\"", "gi"); // Loop through all of the ms-formbody table cells $("td.ms-formbody").each(function() { // Check for the right comment if(searchText.test($(this).html())) { $(this).find("div[Title='People Picker']").html(managerName); return false; } }); }); // End $(document).ready
In line 8, you can change the value Manager to anything else you’d like to get back from the GetUserProfileByName operation, and in line 14, you could change the Fieldname to whatever your column name for the Manager might be.
The available values from GetUserProfileByName in my test MOSS environment are:
- UserProfile_GUID
- AccountName
- FirstName
- LastName
- PreferredName
- WorkPhone
- Office
- Department
- Title
- Manager
- AboutMe
- PersonalSpace
- PictureURL
- UserName
- QuickLinks
- WebSite
- PublicSiteRedirect
- SPS-Dotted-line
- SPS-Peers
- SPS-Responsibility
- SPS-Skills
- SPS-PastProjects
- SPS-Interests
- SPS-School
- SPS-SipAddress
- SPS-Birthday
- SPS-MySiteUpgrade
- SPS-DontSuggestList
- SPS-ProxyAddresses
- SPS-HireDate
- SPS-LastColleagueAdded
- SPS-OWAUrl
- SPS-ResourceAccountName
- SPS-MasterAccountName
- Assistant
- WorkEmail
- CellPhone
- Fax
- HomePhone
Marc, how can I see returned XML?
Thanks.
You can use the IE Developer Tools, Fiddler, or Firebug to look at the net traffic directly. Or use an alert to pop the values up in the browser.
M.
Marc,
result output XML:
…
falsefalseManagerPublicDOMAIN\user
…
As shown there is a column filled, but I can not get “Manager” value
Vitaly:
As you can see, the XML doesn’t post well here. If you’d like, post your question over in the SPServices Discussions. You can easily add and format code there. From the looks of what you show above, you’re just not selecting for the Manager correctly in your code.
M.
I found this solution to prefill a peoplepicker field (like the Manager).
It works perfectly!
$(“textarea[title=’People Picker’]”).val(userName);
$(“div[title=’People Picker’]”).text(userName);
http://tanveerkhan-sharepoint.blogspot.se/2011/09/populate-current-logged-in-user-name-in.html
HR
HR:
You’ll be fine with that code as long as there is only one People Picker in the page. If there are multiple People Pickers or you’d just like to let SPServices do the work for you, check out the $().SPServices.SPFindPeoplePicker function.
M.
Ok I see, thanks for the information!
Hi Marc,
A brilliant library, thanks so much for what you have given to the community
Something that has puzzled me for a long time, is how would you possibly list the direct reports of a manager. It seems impossible to achieve through client side scripting (either through webservices with spservices or with the client object model)
After many hours scouring, I cant find anyone on the internet trying to achieve this client side which is amazing!
Is there any call where you can pass in the Manager as a parameter in the CAML query?
Would you know of any possible solution?
Jack:
I tried to monkey something together on this, but the Web Services just don’t give us the capabilities to do it.
M.
Great Post.
Hi,
I am getting this error in google chrome :(
POST url/_vti_bin/UserProfileService.asmx 500 (Internal Server Error)
Please help !!
Varun:
Can you post more details on the SPServices discussions?
M.
Sure marc Thanks!
Hi Marc,
I am getting the Display Name(Anil Yadagiri) from the people picker using following query.
var user = $.trim($(“#content”).text());
Now i need to get the Account Name(Domain\\username) of the user.So that i can pass it to the sp services to get the manager of that particular user.
Can you please help me on this requirement.
Regards,
Anil
Anil:
Too many comments! One would do it. Have you looked at SPFindPeoplePicker in SPServices? Using that you can get the user’s ID and then query the User Information List. If you have questions, please post them on the Codeplex Discussions.
M.
I need to something like that, but never enter to each loop.
SP.SOD.executeOrDelayUntilScriptLoaded(initializeUser,”sp.js”)
function initializeUser(){
var ctx=SP.ClientContext.get_current();
var web=ctx.get_web();
var list=web.get_lists().getByTitle(“Weekly Status”);
user=web.get_currentUser();
ctx.load(user);
ctx.executeQueryAsync(Function.createDelegate(this,userSuccess),Function.createDelegate(this,onFail))
}
function userSuccess(){
var columnName = ‘Updated By’;
var userName = ‘domain\\username’;
var userName = user.get_title();
var searchText = RegExp(“FieldName=\”” + columnName + “\””, “gi”);
$(“td.ms-formbody”).each(function() {
if(searchText.test($(this).html())) {
$(this).find(“div[Title=’People Picker’]”).html(userName);
return false;
}
});
Thanks Marc. your code helped me a lot.
use this script
$(document).ready(function () {
GetUserLogin();
});
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + “/_api/web/getuserbyid(” + userid + “)”;
var requestHeaders = { “accept” : “application/json;odata=verbose” };
$.ajax({
url : requestUri,
contentType : “application/json;odata=verbose”,
headers : requestHeaders,
success : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
var loginName = data.d.LoginName.split(‘|’)[2];
document.getElementById(‘ctl00_ctl61_g_b428fe72_1aaf_4df3_8ac7_319bb5ab6b15_ctl00_ctl05_ctl01_ctl00_ctl00_ctl05_ctl00_ctl00_UserField_upLevelDiv’).innerHTML = loginName;
document.getElementById(‘ctl00_ctl61_g_b428fe72_1aaf_4df3_8ac7_319bb5ab6b15_ctl00_ctl05_ctl01_ctl00_ctl00_ctl05_ctl00_ctl00_UserField_checkNames’).click();
}
function QueryError(error) {
alert(error);
}