Link to fill user login name in people picker

By request from Charlie:

Hi:
Similar to the “Date Picker Clicker”, do you know if I could click a link and the users login name would fill a People Picker (person or group)?… on a newform or editform?

Charlie Epes

Here is a solution for inserting current user’s login name in a people picker by clicking on a link above the field.

IMG

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The file “AccessUserProfileInWSS.js” is found here. Read the article as you have to set your “user list GUID” in the script.

The code for the file “SetPeoplePicker.js” is found below.

Add a CEWP below – it is essential that it is placed below – your list-form as described here, and add this code:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
<script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
<script type="text/javascript" src="/test/English/Javascript/AccessUserProfileInWSS.js"></script>
<script type="text/javascript" src="/test/English/Javascript/SetPeoplePicker.js"></script>
<script type="text/javascript">
// Array of fields to add this function to
  var arrOfFields = ['MyPeoplePicker','AnotherPeoplePicker'];
  initSetPeoplePicker(arrOfFields);
</script>

The code for the file “SetPeoplePicker.js” looks like this:

/* Set people picker to current user login by click on a link above the field
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * v1.0
 * LastMod: 04.12.2009
 * ---------------------------------------------
 * Include reference to jquery - http://jquery.com
 *  interaction.js - http://spjslib.codeplex.com/
 *  stringBuffer.js - http://spjslib.codeplex.com/
 *  AccessUserProfileInWSS.js - https://spjsblog.com/2009/09/20/accessing-user-profile-information-in-wss-3-0-with-javascript/
 * ---------------------------------------------
 * Call from a CEWP below the list form in NewForm or EditForm like this:
	<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/AccessUserProfileInWSS.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/SetPeoplePicker.js"></script>
	<script type="text/javascript">
	// Array of fields to add this function to
	  var arrOfFields = ['MyPeoplePicker','AnotherPeoplePicker'];
	  initSetPeoplePicker(arrOfFields);
	</script>
*/

// Build the user information object
var ui = getUserInfo();

function initSetPeoplePicker(arr){
if(typeof(fields)=='undefined')fields = init_fields();
	$.each(arr,function(idx,item){
		// Check if FieldInternalName is correct
		if(fields[item]==undefined)return;
		// Add clickable link over field - ui.Title=DisplayName of current user
		$(fields[item]).find('.ms-formbody').prepend("<div><a title="Set field's value to " + ui.Title + "" href="javascript:setPeoplePicker('" + item + "')">[" + ui.Title + "]</a></div>");	
	});
}

function setPeoplePicker(FieldInternalName){
var field = $(fields[FieldInternalName])
	if(field.find('.ms-inputuserfield:visible').length>0){	
		// IE
		field.find('.ms-inputuserfield').html(ui.Name);
		field.find('img:first').click();	
	}else{
		// FF
		field.find("textarea:first").val(ui.Name);
	}
}

function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return; 
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7; 
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}

Save this code as “SetPeoplePicker.js”, and upload to the script library as shown above.

Ask if something is unclear.

Regards
Alexander

36 thoughts on “Link to fill user login name in people picker”

  1. This is great. I have not implemented it yet, but I am sure it is perfect. So can the functionality be extented to additional fields? With the click can we also populate email, phone, manager etc. or when the people picker is populated, whether by clicking my name or selecting a new name, these other fields get populated based on the people picker results.
    Is this possible?

    1. Hi,
      ui = getUserInfo(); returns an object containing the information from the WSS user profile:
      ‘ID’, ‘Name’, ‘Title’, ‘EMail’, ‘Department’, ‘JobTitle’, ‘Notes’, ‘Picture’,
      ‘IsSiteAdmin’, ‘Created’, ‘Author’, ‘Modified’, ‘Editor’, ‘SipAddress’, ‘Deleted’.

      The values from the “object” is accessed like this for “login name”:
      ui.Name

      Like this for DisplayName:
      ui.Title

      And so on.

      The “ui”-object is called with the id of the user you want to access. If id is not supplied – it returns current user.

      Alexander

  2. I replace line 37 with this code. This automatically loads the logged in user.

    $(window).load(function(){
          setPeoplePicker(item);
    });
    

    I have 2 more people picker fields. a manager and 2nd level manager. Is there a way to use the functionality of your cascading dropdowns and populate the next 2 people pickers using an external list. I know your cascading dropdows use text fields, can people pickers be used in place, and auto populate them.

    1. Hi,
      I do not think a cascading dropdow would be it, but if you have a list where you have a column with the user id, and another column with the manager and a third with the 2 level manager (each of them people pickers), you could do a javascript query to get those id’s, and then put them into the people pickers as you did with the current.

      To get this working however, you would need to have a list complete with all user ids and their managers.

      On MOSS you could query the MOSS SSP Profile, but in WSS there is no such AD-sync.

      Alexander

    2. This is promising. Will not upgrade to MOSS for 6 months., but if I read your reply correctly as long as I have a complete list I could query that list and populate the people picker for each level manager, right?
      do you know of any examples of something like this, maybe on a smaller scale?

    3. Hi,
      This example gives you an array of the users in the format useiID;#UserName

      You have to refer the scripts “interaction.js” and stringBuffer.js” found here.

      This example uses a list “ManagerList”, with three fields “User”, “Manager”, and “Manager2”.

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript" src="../../Javascript/interaction.js"></script>
      <script type="text/javascript" src="../../Javascript/stringBuffer.js"></script>
      <script type="text/javascript">
      var userAndManager = getManager('ManagerList','User',_spUserId,['User','Manager','Manager2']);
      alert(userAndManager);
      
      function getManager(listNameOrGuid,FieldInternalName,userId,arrOfViewFields){
      	wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
      	var query = "<Where><Eq><FieldRef Name='" + FieldInternalName + "' LookupId='True'/><Value Type='User'>" + userId + "</Value></Eq></Where>";
      	var res = queryItems(listNameOrGuid,query,arrOfViewFields,1);
      		var item = res.items[0];
      		var ret = [];
      		$.each(arrOfViewFields,function(i,fin){
      			ret.push(item[fin]);
      		});
      		return ret;
      }
      </script>
      

      You would have to split the returned values and process the userId with the function “getUserInfo()” to get the login name as in the original script above.

      Alexander

    4. this is a great start, thanks so much. I know you gave just a quick high level overview, so I have a few quick questions.
      in the ManagerList, are the fields people picker or single line text? the value returned will be from all fields I will need to parse them out, right?

    5. Hi,
      The fields are people pickers. The result is an array.
      Replace line 6 in example above with this:

      $.each(userAndManager,function(i,item){
        var split = item.split(';#');
        var userID = split[0];
        var dispName = split[1];
        // Do something with userID here - alert it for now
        alert("UserID="+userID+"nDisplayName="+dispName);
      });
      

      Alexander

    6. Perfect, Now this should give an alert, whuch is not firing off. On line 11 do I need to replace any thing, like listNameOrGuid with my listname? I even created a new list named ManagerList with the fields User, Manager, Manager2 all people picker fields. Placed the script on my form page, but no alert

      I am sorry to be a pest

    7. Yes I have it below the form running in parallel with the people picker script. and a few other scripts.

      The alert should just fire off. right? Should I remove the other scripts?

  3. yes that worked and I think I see what my issue is. my target list has a field named “email” which I am going to change to User.

    Can I use the setpeoplepicker scrip to right these values to the 3 fields?

    1. You have to send the user id trough the function “getUserInfo(theUserIdIsPutHere)” to get the login name as in the original script above.

      When filling a people picker via “setpeoplepicker” you have to use the loginame.

      Alexander

    2. I really appreciate all your input and time. This will take some doing. I am no where near the developer you are, but I will let you know what I come up with.

      thanks,
      Larry

    3. I am adding the getUserInfo(theUserIdIsPutHere). I see the loop $each(userAndManager)

      I am not sure how to grab each UserId, and I am not sure how to write it to the different fields
      First value write to User
      Second value write to Manager
      Third value write to Manager2

    4. Hi,
      I have wrapped it up for you like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript" src="../../Javascript/interaction.js"></script>
      <script type="text/javascript" src="../../Javascript/stringBuffer.js"></script>
      <script type="text/javascript" src="../../Javascript/AccessUserProfileInWSS.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      // FieldInternalNames from manager list
      var arrOfFieldInternalNamesInManagerList = ['Manager','Manager2'];
      // FieldInternalNames from this list to writ the data back to
      var arrOfFieldInternalNamesInThisList = ['Manager1','Manager2'];
      // Hide all the people picker fields
      $.each(arrOfFieldInternalNamesInThisList,function(i,fin){
      	$(fields[fin]).hide();
      });
      // Get managers for current user - "_spUserId" is current user
      var userAndManager = getManager('ManagerList','User',_spUserId,arrOfFieldInternalNamesInManagerList);
      
      // Wait until page has finished loading, then fill the manager fields
      $(document).ready(function(){
      	$.each(userAndManager,function(i,item){
      		var split = item.split(';#');
      		var userID = split[0];
      		var dispName = split[1];
      		var ui = getUserInfo(userID);
      		// Set the people pickers value on load
      		setPeoplePicker(arrOfFieldInternalNamesInThisList[i],ui.Name);
      	});
      });
      
      // Function to set the people picker value - slighly modifid to handle hidden fields
      function setPeoplePicker(FieldInternalName,loginName){
      var field = $(fields[FieldInternalName])
      	if(field.find('.ms-inputuserfield').css('display')!='none'){
      		// IE
      		field.find('.ms-inputuserfield').html(loginName);
      		field.find('img:first').click();
      	}else{
      		// FF
      		field.find("textarea:first").val(loginName);
      	}
      }
      
      // Custom function to pull managers from anoher list based upon current users ID
      function getManager(listNameOrGuid,FieldInternalName,userId,arrOfViewFields){
      	wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
      	var query = "<Where><Eq><FieldRef Name='" + FieldInternalName + "' LookupId='True'/><Value Type='User'>" + userId + "</Value></Eq></Where>";
      	var res = queryItems(listNameOrGuid,query,arrOfViewFields,1);
      		var item = res.items[0];
      		var ret = [];
      		$.each(arrOfViewFields,function(i,fin){
      			ret.push(item[fin]);
      		});
      		return ret;
      }
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      This script uses current users id (_spUserId) and queries a list called “ManagerList” for the information in the fields specified in the array named “arrOfFieldInternalNamesInManagerList”.

      It then takes the returned values, splits them to get the userId, and uses the function “getUserInfo” to pull the loginName from the user list. It then fills the appropriate people picker (given from the array “arrOfFieldInternalNamesInThisList”) with the loginName.

      Refer this article:
      Accessing user profile information in WSS 3.0 with javascript

      Alexander

    5. Thanks you so much… you saved my ass. I needed to make a few tweaks for tweaks to work.
      line 8: arrOfFieldInternalNamesInManagerList – I needed to add the field that contained the end user
      line 10: arrOfFieldInternalNamesInThisList – same I needed to add the corresponding end user field
      and the closing script tag was missing”>”

      you hide the fields, and that worked perfectly. this was perfect.

      Again thank you so much

  4. Original script, I am reading thru the script to try and figure out how one click, will populate the arrOfFields instead of a single click on each field. I can see how the function works to populate a field, but cant figure out how to make it single click populate all people picker fields. Is this something easy or require some work?

  5. Hi Alexander,

    This script isn’t pointing the current user for me. It’s pointing to seemingly random people. Any idea why this is happening?

    Thanks!
    Katie

    1. Hi,
      That is strange. The link is created based on the variable “_spUserId” that reflects the logged in user.

      I presume it is not anonymous access to the list?

      Alexander

    2. No, only our department has access to the list, but it’s pulling a seemingly random person within the entire organization. This would be amazing if I could get it to work! Does anything look wrong with the Access User Profile script that would get the correct user name?

      function getUserInfo(UserId){
      wsBaseUrl = ‘/_vti_bin/’;
      var uiObj = {};
      if(typeof(UserId)==”undefined” || UserId==”)UserId = _spUserId;
      var arrOfFields = [‘ID’, ‘Name’, ‘Title’, ‘EMail’, ‘Department’, ‘JobTitle’, ‘Notes’, ‘Picture’,
      ‘IsSiteAdmin’, ‘Created’, ‘Author’, ‘Modified’, ‘Editor’, ‘SipAddress’, ‘Deleted’];
      var item = getItemById(‘UserInfo’,UserId,arrOfFields);
      if(item != null){
      for(i=0;i<arrOfFields.length;i++){
      if(item[arrOfFields[i]]!=null){
      uiObj[arrOfFields[i]] = item[arrOfFields[i]];
      }else{
      uiObj[arrOfFields[i]] = '';
      }
      }
      return uiObj;
      }else{
      for(i=0;i<arrOfFields.length;i++){
      uiObj[arrOfFields[i]] = "User with id " + UserId + " not found.";
      }
      return uiObj;
      }
      }

    3. Hi,
      This script relies on the SharePoint variable “_spUserId” to identify the user. Has the master page been changed in a way that messes with this variable?

      Try alerting the variable like this:
      alert(_spUserId);
      and compare the id with your ID from “My settings” – look at the URL for …/_layouts/userdisp.aspx?Force=True&ID=1

      Alexander

  6. I don’t even know how I ended up here, but I thought this post was good. I don’t know
    who you are but definitely you are going to a famous blogger if you
    are not already 😉 Cheers!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.