GetUserProfileByName

Dec 15, 2009 at 12:22 PM

I can't find any example of using SPService to call the GetUserProfileByName service. Is it possible to show an example of using this to populate other fields?

Coordinator
Dec 15, 2009 at 3:50 PM

You're not finding an example because I don't have one! Building an example for every Web Service operation that I've wrapped would take forever.  If you can explain what you are interested in doing, perhaps we can work through it together and the result could become an example for others.

The general syntax (bottom of the page) for calling the $().SPServices functions should give you enough to get started.

M.

Dec 15, 2009 at 9:01 PM

Thanks for your reply. I have a custom list form with a SharePoint:PeopleEditor control. In the OnValueChangedClientScript I would like to be able to call your SPService to populate additional User Profile properties on the same form, such as Location.

Dec 16, 2009 at 2:19 AM

Is done.

In my UserControl I added an OnValueChangedClientScript attribute:

<SharePoint:PeopleEditor ID="txtDelegateName" runat="server" MultiSelect="false" Width="250px" AllowTypeIn="false" AllowEmpty="true" OnValueChangedClientScript="txtDelegateName_onChange();" ShowButtons="true" />   

The JavaScript function is then:                  

function txtDelegateName_onChange()
{                            
            var oTxtDelegate = document.getElementById('ctl00$PlaceHolderMain$PropertyServicesRequestItem$CostCenter$txtDelegateName$downlevelTextBox');
        
            $().SPServices({
    	        operation: 'GetUserProfileByName',
	            AccountName: oTxtDelegate.value,
	            async: false,
	            completefunc: function (xData, Status) 
                {		        		        
                    var properties = xData.responseXML.getElementsByTagName('PropertyData');  
                    
                    var propertyValues = new Array();  
                    for (var i=0; i < properties.length; i++)  
                    {  
                       var propName = properties[i].getElementsByTagName('Name')[0].childNodes[0].nodeValue;                                        
                       propertyValues[propName] = properties[i].getElementsByTagName('Value');  
                       
                       var oValueNode = properties[i].getElementsByTagName('Value');    
                       if(oValueNode.length > 0)
                       {
                            propertyValues[propName] = oValueNode[0].childNodes[0].nodeValue;
                       }
                       else
                       {
                            propertyValues[propName] = '';
                       }                                           
                    }      
                     		        
                    //set form values              

                    document.getElementById('ctl00_PlaceHolderMain_PropertyServicesRequestItem_CostCenter_txtDelegatePhone').value = propertyValues['WorkPhone'];                
                    document.getElementById('ctl00_PlaceHolderMain_PropertyServicesRequestItem_CostCenter_txtDelegateBusinessDivision').value = propertyValues['Department'];
                    document.getElementById('ctl00_PlaceHolderMain_PropertyServicesRequestItem_CostCenter_txtDelegateBranch').value = propertyValues['Branch'];
                    document.getElementById('ctl00_PlaceHolderMain_PropertyServicesRequestItem_CostCenter_txtDelegateSection').value = propertyValues['Section'];
                    document.getElementById('ctl00_PlaceHolderMain_PropertyServicesRequestItem_CostCenter_txtDelegateEmail').value = propertyValues['WorkEmail'];
                    
	            }
            });
        }  

I actually render the JavaScript with the UserControl and substitute in all the control clientIDs but have replaced above for readability.

Thanks for a great library.

 

Coordinator
Dec 16, 2009 at 2:43 PM

Great! Sorry I wasn't able to be of more help along the way.

You could tighten up the code in completefunc by using more jQuery, but if it works for you then that's the important thing, as it's yours to support.

Let me know if I can be of any further help.

M.

Sep 2, 2010 at 1:42 AM
Edited Sep 2, 2010 at 1:48 AM

Nice, works great!

I had a few more requirements, so I thought I'd post my code

  1. Not only do I populate text input boxes, but I also needed to query a second user (The first persons manager) and fill in his info after the first lookup is fired.
  2. I also had to populate profile info to a drop down with other static options and mark their's as selected.
  3. I couldnt get #1 automated, so once the first event fires, you need to click "check names" on the manager people lookup.

Very great post though, here's my modifications:

<script>
///////////////////////////////
//* START Target User Profile lookup *//
///////////////////////////////
 
function targetUserNGID_onChange()
{  
 var oTxtDelegate = document.getElementById('ctl00$PlaceHolderMain$targetUserNGID$downlevelTextBox');
        
            $().SPServices({
    	        operation: 'GetUserProfileByName',
	            AccountName: oTxtDelegate.value,
	            async: false,
	            completefunc: function (xData, Status) 
                {		        		        
                    var properties = xData.responseXML.getElementsByTagName('PropertyData');  
                    
                    var propertyValues = new Array();  
                    for (var i=0; i < properties.length; i++)  
                    {  
                       var propName = properties[i].getElementsByTagName('Name')[0].childNodes[0].nodeValue;                                        
                       propertyValues[propName] = properties[i].getElementsByTagName('Value');  
                       
                       var oValueNode = properties[i].getElementsByTagName('Value');    
                       if(oValueNode.length > 0)
                       {
                            propertyValues[propName] = oValueNode[0].childNodes[0].nodeValue;
                       }
                       else
                       {
                            propertyValues[propName] = '';
                       }                                           
                    }      
                     		        
                    //set form values              
 
                    document.getElementById('targetUserMyID').value = propertyValues['WorkPhone'];                
                    document.getElementById('targetUserLoginID').value = propertyValues['WorkPhone'];   
                                 
                    document.getElementById('targetUserLastName').value = propertyValues['LastName'];                
                    document.getElementById('targetUserFirstName').value = propertyValues['FirstName'];        
                            
                    document.getElementById('targetUserEmail').value = propertyValues['WorkEmail'];         
                    document.getElementById('targetUserDepartment').value = propertyValues['Department'];   
                    
                    document.getElementById('targetUserJobFunction').value = propertyValues['Title'];      
					var text = propertyValues['WorkPhone']; //creates drop down value and text for targetUserSector
									    $('#targetUserSector').append( 
				        $('<option selected=selected></option>').val(val).html(text) 
				    ); 
				    //$('#targetUserSector').focus(); // forces validation when appending sector, that way user sees the error right away.
 
                                        
                    document.getElementById('targetUserPhone').value = propertyValues['WorkPhone'];       
                    document.getElementById('targetUserFax').value = propertyValues['Fax']; 
                    
                    
		//set manager, thanks marc, http://sympmarc.com/2010/03/16/set-a-people-pickers-value-on-a-form-revisited-with-jquery/
		$('#ctl00_PlaceHolderMain_targetUserManagerNGID_upLevelDiv').html(propertyValues['Manager']);
 					
 		//clear old manager name and email
              	document.getElementById('targetUserManagerName').value = '';                
                    document.getElementById('targetUserManagerEmail').value = '';  
                    
	            }
            });
 
} //end function
///////////////////////////////
//* END Target User Profile lookup *//
///////////////////////////////

///////////////////////////////
//* START Manager Profile lookup *//
///////////////////////////////
 
function targetUserManagerNGID_onChange()
{  
 var oTxtDelegate = document.getElementById('ctl00$PlaceHolderMain$targetUserManagerNGID$downlevelTextBox');
        
            $().SPServices({
    	        operation: 'GetUserProfileByName',
	            AccountName: oTxtDelegate.value,
	            async: false,
	            completefunc: function (xData, Status) 
                {		        		        
                    var properties = xData.responseXML.getElementsByTagName('PropertyData');  
                    
                    var propertyValues = new Array();  
                    for (var i=0; i < properties.length; i++)  
                    {  
                       var propName = properties[i].getElementsByTagName('Name')[0].childNodes[0].nodeValue;                                        
                       propertyValues[propName] = properties[i].getElementsByTagName('Value');  
                       
                       var oValueNode = properties[i].getElementsByTagName('Value');    
                       if(oValueNode.length > 0)
                       {
                            propertyValues[propName] = oValueNode[0].childNodes[0].nodeValue;
                       }
                       else
                       {
                            propertyValues[propName] = '';
                       }                                           
                    }      
                     		        
                    //set form values              
 
                    document.getElementById('targetUserManagerName').value = propertyValues['PreferredName'];                
                    document.getElementById('targetUserManagerEmail').value = propertyValues['WorkEmail'];   
                                 
                                        
	            }
            });
 
} //end function
///////////////////////////////
//* END Manager Profile lookup *//
///////////////////////////////

</script>
 
<SharePoint:PeopleEditor ID="targetUserNGID" runat="server" MultiSelect="false" Width="250px" AllowTypeIn="true" AllowEmpty="true" OnValueChangedClientScript="targetUserNGID_onChange();" ShowButtons="true"/>


<
input name="targetUserMyID" type="text" />

 etc for each input field.


<select name="targetUserSector" id="targetUserSector">
  <option value="none"  selected="selected">Ipsum1</option>
  <option value="none">Ipsum2</option>
  <option value="none">Ipsum3</option>
  <option value="none">Ipsum4</option>
  <option value="none">Ipsum5</option>
  </select>
The second people lookup:
<SharePoint:PeopleEditor ID="targetUserManagerNGID" runat="server" MultiSelect="false" Width="250px" AllowTypeIn="true" AllowEmpty="true" OnValueChangedClientScript="targetUserManagerNGID_onChange();" ShowButtons="true"/>

<input name="targetUserManagerName" type="text" class="required" />

<input name="targetUserManagerEmail" type="text" class="required" />

here is the complete list of default profile properties get returned by the userprofileservice. I think they are pretty self explained: (from http://blogs.microsoft.co.il/blogs/itaysk/archive/2007/04/05/InfoPath-_2D00_-Get-the-current-user-without-writing-code.aspx)

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

 

Sep 22, 2010 at 3:36 AM

Instead of using Javascript you can use jquery to find the xml node. example:

completefunc: function (xData, Status) {
$(xData.responseXML).find("PropertyData").each(
    function()
     {
        
         if (($(this).find("Name").text()) === "Title")
           {
         title = $(this).find("Value").text();
         alert(title);
           }
          
            if (($(this).find("Name").text()) === "Manager")
           {
         manager = $(this).find("Value").text();
           alert(manager);
           }

    });

Oct 18, 2010 at 1:15 PM

I wanted to put a simple wrapper on this to give me an object with properties for each of the user profile values.  This code *works* but in IE8 I get an error but my IE debugger says there's no source code for the error.

In IE9, Chrome and Firefox I get no errors at all.

This is running on SharePoint 2010.

$TS.GetUserProperties = function(LoginID, Callback)
 {
  if (!window.jQuery.fn.SPServices) { throw "This function requires you to reference the SPServices script file.";}
  
  // Run async if a callback is specified.
  var lbAsync = (Callback !== undefined)? true : false;

  $().SPServices({
   operation: 'GetUserProfileByName',
   AccountName: LoginID,
   async: lbAsync,
   completefunc: function (xData, Status)
   {
    $TS.UserProperties = [];
    $(xData.responseXML).find("PropertyData")
    .each(function(lcv, o)
     {
      var $o = $(o);
      var lsName = $o.find("Name").text() || "";
      if (lsName.length)
      {
       var lsValue = $o.find("Value").text() || "";
       $TS.UserProperties[lsName] = lsValue;
      }
     });
     
    if (Callback) { Callback(); };   
   }
  });
 };

Any suggestions on what I'm doing wrong?

Coordinator
Oct 20, 2010 at 3:19 AM

It's hard to say. Have you tried using the debugger in the IE8 Developer Tools? If there's an error, it will help you pinpoint where it is occurring.

M.

Oct 27, 2010 at 5:49 PM

 I want to populate a manager field from the UserProfileService on a default newform.aspx. How do I modify this code to fit my requirement?

Coordinator
Oct 28, 2010 at 12:04 AM
RLilly: I'm not sure that starting with this code is the best way to go. Try just setting up something simple to get started, and post back in a new thread if you have questions. M.
Dec 10, 2011 at 2:30 PM

Marc, isn't this code more efficient than the existing method used to get the current user details? The current hack using the userprofile page is really heavy and makes a lot of HTTP calls in the background (including loading a bunch of CSS and JS files which are never used).

 

Coordinator
Dec 10, 2011 at 2:32 PM
Edited Feb 14, 2012 at 1:43 PM

Indeed it is, but only if you have the Standard or Enterprise CALs. I wanted to offer up a way to get user details for people using WSS or Foundation as well.

M.

Feb 9, 2012 at 8:40 AM
Edited Feb 16, 2012 at 10:24 AM

If this helps anyone, here is a simple version I use to fetch user details:

function get_user_profile_by_login(login) {
    var user = {};
    
    var params = {
        operation: 'GetUserProfileByName',
        async: false,
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("PropertyData").each(function() {
                user[$(this).find("Name").text()] = $(this).find("Value").text();                
            }); // end each

            // Easy names
            user.login = user.AccountName;
            user.full_name = user.PreferredName;
            user.email = user.WorkEmail;

        } // end completefunc
    };
    
    if (login != null) {
        params.AccountName = login;
    };
    
    $().SPServices(params);

    return user;
}

function get_current_user() {
    return get_user_profile_by_login(null);
};

Coordinator
Feb 14, 2012 at 1:45 PM

Thanks a lot for posting this. I'm going to post it as an example for the GetUserProfileByName operation, as well as in a blog post.

M.

Mar 5, 2012 at 8:14 PM
Edited Mar 5, 2012 at 8:15 PM

Can someone give an example of how to populate a text box with the current users display name?

 

Coordinator
Mar 6, 2012 at 12:00 AM

Something like this:

var thisUser = $().SPServices.SPGetCurrentUser({
  fieldName: "Name"
});
$("input[title='yourtitle']").html(thisUser);

M.

Jul 9, 2012 at 7:30 PM
Edited Jul 9, 2012 at 7:48 PM

Marc - Please help! Perhaps I do not see the forest for the trees...

[see code below my sig]

userManagerName is undefined

Thanks!

=Preso

 


 

 

$(document).ready(function(){ 
 
var userManager=$().SPServices.SPGetCurrentUser({fieldName: "Manager", debug: false});
var manager = get_user_profile_by_login(userManager);
var userManagerName	= manager.full_name;
alert (userManagerName);
});

function get_user_profile_by_login(login) {
  var user = {};
  var params = {
    operation: 'GetUserProfileByName',
    async: false,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("PropertyData").each(function() {
        user[$(this).find("Name").text()] = $(this).find("Value").text();
      }); // end each
      // Easy names
      user.login = user.AccountName;
      user.full_name = user.PreferredName;
      user.email = user.WorkEmail;
    } // end completefunc
  };
  if (login != null) {
    params.accountName = login;
  } else {
    params.accountName = $().SPServices.SPGetCurrentUser({
      fieldName: "Name"
    });
  }
  
  $().SPServices(params);
  return user;
}

Coordinator
Jul 10, 2012 at 2:02 AM

Are you getting a value for userManager? Note that Manager is not one of the options available from the function: http://spservices.codeplex.com/wikipage?title=$().SPServices.SPGetCurrentUser

M.

Jul 10, 2012 at 5:46 PM
Edited Jul 10, 2012 at 5:47 PM

Thanks Marc - yes I am getting a response of the currently logged in user's manager in the form of "DOMAIN\samAccountName" e.g. "CORP\espreso"

Also, when I put in an alert here (this goes into function get_user_profile_by_login(login)):

function get_user_profile_by_login(login) {
  alert("Line 405 get_user_profile_by_login: "+login);
  var user = {};
...
I get the manager samAccountName also. However, when I put this alert in (again function get_user_profile_by_login(login)), it returns undefined:
  $().SPServices(params);
  alert ("Line 428 manager full name: "+user.full_name);
  return user;
}
Coordinator
Jul 10, 2012 at 8:05 PM

I'd suggest adding an alert before the line:

 $(xData.responseXML).SPFilterNode...

like

alert(xData.responseText);

This will show you the XML returned by the server.

M.

Nov 13, 2012 at 6:27 PM
Edited Nov 13, 2012 at 6:27 PM

Is this function only availabe for use when using MOSS or both MOSS 2007 & WSS? That is what I understand from the documentation on it. We don't use MOSS 2007, only WSS (we're pretty "thumbed under") but still would've liked to have some of the user's AD fields accesssbile in order to set defaults on certain other fields

Thanks

Coordinator
Nov 15, 2012 at 5:15 PM

Carl:

If you look at the core SPServices documentation page, you'll be able to see that the User Profile Service is only available in MOSS.

M.

Feb 14, 2013 at 3:17 PM
Hi,

i am having a problem with GetUserProfileByName. ill explain what i am actually trying to accomplish and then ill explain my problem.

i have an input field that on keydown it searches profile Service and returns the staff member that is close to that name that you are typing.

problems: when i try search for a name like John i get no results back, but when i put John.Martinez i get back results. is there a way for me to fix that? i want it to search by last name or first name. what ever the user starts typing.

i want the result to just return 5 records at a time until it gets to only one. how can i do that. below is the code i am using. i actually used the code that i found here and modified it so that it can do what i want it to do.
<input name="userSearch" type="text" id="userSearch" onkeydown="getStaffInformation(this.value)" /><br/><br/>
<div id="staffInformationList"> </div>
function getStaffInformation(name)
{
        $().SPServices({
            operation: 'GetUserProfileByName',
            AccountName: name,
            async:false,
            completefunc: function (xData, Status)
            {
                var properties = xData.responseXML.getElementsByTagName('PropertyData');
                var propertyValues = new Array();
                
                for(var i=0; i < properties.length; i++)
                {
                    var propName = properties[i].getElementsByTagName('Name')[0].childNodes[0].nodeValue;                                        
                    
                    propertyValues[propName] = properties[i].getElementsByTagName('Value');  
                    
                    var oValueNode = properties[i].getElementsByTagName('Value');
                        
                    if(oValueNode.length > 0)
                    {
                        propertyValues[propName] = oValueNode[0].childNodes[0].nodeValue;
                    }
                    else
                    {
                        propertyValues[propName] = '';
                    }                       
                }//end of for loop
                                
                var searchName  = propertyValues['PreferredName'];
                var seachTitle  = propertyValues['Title'];
                var searchEmail = propertyValues['WorkEmail'];
                var searchPhoto = propertyValues['PictureURL'];
                var searchPhone = propertyValues['WorkPhone'];
                
                //alert(searchName);
                
                var seachInformation = "<li>"
                                       +"<table width=\"250\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
                                       +"<tr>"
                                       +"<td width=\"48\" rowspan=\"3\" valign=\"top\">"+
                                       +"<div class=\"searchPicture\"><img alt=\"\" src=\""+searchPhoto+"\" /></div>"
                                       +"</td>"
                                       +"<td width=\"154\" height=\"16\" valign=\"top\">"+searchName+"</td>"
                                       +"<td width=\"44\" rowspan=\"2\" align=\"right\" valign=\"top\">"
                                       +"<a href=\"mailto:"+searchEmail+"\"><img src=\"/sites/247Dev/SiteAssets/images/email.png\" width=\"22\" height=\"15\" alt=\"Email\" border=\"0\" /></a>"
                                       +"</td>"
                                       +"</tr>"
                                       +"<tr>"
                                       +"<td height=\"16\" valign=\"top\">"
                                       +"<span class=\"searchTitle\">"+seachTitle+"</span>"
                                       +"</td>"
                                       +"</tr>"
                                       +"<tr>"
                                       +"<td valign=\"16\">"
                                       +"<span class=\"searchPhone\">"+searchPhone+"</span>"+
                                       +"</td>"
                                       +"<td valign=\"top\">&nbsp;</td>"
                                       +"</tr>"
                                       +"</table>"
                                       +"</li>";
                               
                $('#staffInformationList').append(seachInformation);
                
            }//end of comple function
        });//end of spservices
    }//end of function  
Coordinator
Feb 14, 2013 at 4:23 PM
There's no operation in the User Profile Service that allows you to retrieve multiple users based on part of their name. You can get colleagues and such, but only for one user.

You might want to try using the User Information List as the source for GetListItems instead. That will only retrieve people who hoave "touched" the current Site Collection, but that may be sufficient for you.

Finally, why not just use a Person or Group coulmn, thus a People Picker?

M.
Feb 14, 2013 at 4:59 PM
thanks for the quick response.

i had a feeling GetUserProfileByName wasn't going to work but i tried it anyways. let me ask you something.

can i do live search on SharePoint 2010? cause that's what i am really trying to do. and what do you mean by "why not just use a Person or Group coulmn, thus a People Picker".

sorry about all these questions but i am fairly new to SharePoint development.
Coordinator
Feb 14, 2013 at 5:26 PM
If you're working in a list form, then you probably should be using a Person or Group column.

Yes, you can call the Search Web Service with SPServices just like any other. Check the docs.

M.