Working with SharePoint People Pickers with jQuery: A New Function Called findPeoplePicker

[notice]2012-09-07 – Note that I’ve added a more robust version of this function into SPServices v0.7.2, which at this writing is in beta but will be released soon. See the docs for SPFindPeoplePicker.[/notice]

I was working with several People Pickers in a form for a client project last week where I needed to set or get their values at various times in the page lifecycle. These things are pesky little compound controls, I often need to find them in the page, and I get tired of writing new script every time I want to do it. I’ve posted in the past about how to get the value with JavaScript, set the value with JavaScript, set one with jQuery, and more. It seemed high time to just write a little function to give me everything I needed in one go.

Here’s what I came up with:

[important]UPDATE 2012-04-24 – I made a dumb mistake by using :contains() in the selector for thisRow, which occasionally returned unwanted results. I fixed it with the .filter() function below.[/important]

// Find a People Picker in the page
// Returns references to:
//   row - The TR which contains the People Picker (useful if you'd like to hide it at some point)
//   contents - The element which contains the current value
//   currentValue - The current value if it is set
//   checkNames - The Check Names image (in case you'd like to click it at some point)
$.fn.findPeoplePicker = function(options) {

  var opt = $.extend({}, {
    peoplePickerDisplayName: "",	// The displayName of the People Picker on the form
    valueToSet: "",			// The value to set the People Picker to. Should be a string containing each username or groupname separated by semi-colons.
    checkNames: true			// If set to true, the Check Names image will be clicked to resolve the names
  }, options);

  // Find the row containing the People Picker
  var thisRow = $("nobr").filter(function() {
    return $(this).text() == opt.peoplePickerDisplayName;
  }).closest("tr");
  var thisContents = thisRow.find("div[Title='People Picker']");
  var thisCheckNames = thisRow.find("img[Title='Check Names']:first");
  if(opt.valueToSet.length > 0) thisContents.html(opt.valueToSet);
  if(opt.checkNames) thisCheckNames.click();
  var thisCurrentValue = thisContents.text();

  return {row: thisRow, contents: thisContents, currentValue: thisCurrentValue, checkNames: thisCheckNames};
}

This function doesn’t just find the People Picker in the form, it also allows you to set it and, if you choose, click the Check Names image automagically. It also returns a JSON object which contains references to the important elements which make up the People Picker so that you can work with them later. Unfortunately, the only thing I can key on to find the darn things in the page is the <nobr> element which contains the DisplayName of the column. There’s just not anything else in the People Pickers which distingishes them from each other other than the standard comment, like so:

<!--  FieldName="Site Contact"
			 FieldInternalName="Site_x0020_Contact"
			 FieldType="SPFieldUser"
		   -->

Uising that comment has always seemed even less reliable to me than the DisplayName, even though I select for it in SPServices in several places. (If I’m missing something, please let me know.)

Here are a few example calls:

// Set the Site Contact to the current user
siteContactPeoplePicker = $().findPeoplePicker({
  peoplePickerDisplayName: "Site Contact",
  valueToSet: $().SPServices.SPGetCurrentUser()
});
// Find the Stakeholders People Picker in the form for later us
stakeholdersPeoplePicker = $().findPeoplePicker({
  peoplePickerDisplayName: "Stakeholders",
  checkNames: false
});

In the first call, I’m setting the Site Contact to the current user and resolving the name. In the second call, I’m getting references to the important objects for the StakeHolders People Picker so that I can set the value variably later, like so:

// Set the Stakeholders column value
stakeholdersPeoplePicker.contents.html(stakeholderNames);
stakeholdersPeoplePicker.checkNames.click();

I think some variation of this would be helpful to add to SPServices, even though it has nothing to do with the Web Services. Would you use it? What else would you want it to do?

Similar Posts

62 Comments

    1. Hein:

      I can’t answer that with certitude. It depends if the markup matches what is found in forms. Best approach would be to try it. If it doesn’t work, clone the function and debug it.

      M.

  1. Marc, I have a people picker field which I need to display the name of a person in a SP group. There will only be one person in this group. I am thinking that the setToValue: is the way to go, but I am lost as to the completion of this function. I have other fields conditionally based on user groups, which just check to see if the current user is in the group and if so, display a certain field. This case is a bit different, and I can’t seem to wrap my head around it. Thanks!

  2. I created custom list new form and have couple of people pickers. Would like to default one of the people picker value to current user.
    However, I am always getting below error
    “Object doesn’t support property or method ‘SPFindPeoplePicker'”

    below is my code
    $(document).ready(function() {
    var thisUserAccount = $().SPServices.SPGetCurrentUser({fieldName: “Name”});
    alert(thisUserAccount);

    $().SPServices.SPFindPeoplePicker({
    peoplePickerDisplayName: “Complete your Name”,
    valueToSet: thisUserAccount,
    checkNames: true
    });

    });

    1. @Swe:

      It looks like you are calling the function correctly. Usually an error like that means your reference to SPServices in’t correct so it isn’t loading into the page. The other possibility is that you’re using a version prior to the one where I added the function – especially if the call to $().SPServices.SPGetCurrentUser is successful.

      M.

  3. As usual, can’t live without SPServices. Combining the get current user function with the find people picker function was a straightforward way to prepopulate a people picker with the current user:

    // prepopulate Allocate To with current user info
    var thisUserAccount = $().SPServices.SPGetCurrentUser({
    	fieldName: "Name",
    	debug: false
    });
    $().SPServices.SPFindPeoplePicker({
      peoplePickerDisplayName: "Allocate To",
      valueToSet: thisUserAccount,
      checkNames: true
    });
    

Leave a Reply

Your email address will not be published. Required fields are marked *

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