1,774 articles and 13,888 comments as of Tuesday, November 23rd, 2010

Tuesday, April 6, 2010

Autocomplete for SharePoint people picker

Guest Author: Alexander Bautz
SharePoint JavaScripts

This solution adds auto complete functionality to a standard SharePoint people picker.


This solution is built with the autocomplete widget from jQuery UI. The values are pulled from the user list based on a query. All users with an email address are available.

Limitations:

  • Single choice only
  • No filter against user group, all users are displayed

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”):


In addition to the above scripts, i have the jQuery UI 1.8 in a separate folder. See the CEWP code and point the links to your jQuery UI location.

The jQuery UI-library is found here. The pictures and the sourcecode refers to jquery-ui-1.8. The autocomplete widget is not found in previous releases.

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.4.min. The autocomplete widget is not supported in previous releases.

The scripts “interaction.js” and “stringBuffer.js” is created by Erucy and published on CodePlex.

The sourcecode for the file “AutocompleteForPeoplePicker.js” is found below.

Read here how to add a CEWP to the NewForm or EditForm, how to find the list Guid of your list, and how to find the FieldInternalName of your columns.

Add a CEWP below the list form in NewForm or EditForm, and insert this code:

<style type="text/css">
.ui-menu .ui-menu-item {
	font-size:xx-small;
}
</style>
<link type="text/css" href="/test/English/jQueryUI18/smoothness/jquery-ui-1.8.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/test/English/Javascript/jquery-1.4.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/jQueryUI18/jquery-ui-1.8.custom.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/AutocompleteForPeoplePicker.js"></script>
<script type="text/javascript">
fields = init_fields();

// Find all users from userlist. Parameters "userListBaseUrl" and "userListGuid"
var allUsers = getUsers('','570D772F-0EAB-45A8-8C54-9CCD4EC6A0AF');

// Call with FieldInternalName of your people picker field(s)
$(document).ready(function(){
	peoplePickerAutoclomplete('MyPeoplePicker');
	peoplePickerAutoclomplete('AnotherPeoplePicker');
});
</script>

Parameters explained:

  • userListBaseUrl: The base URL of the site the user list resides. If your site is in a managed path, it must reflect this managed path. If not, this parameter is most likely an empty string (“”)
  • userListGuid: The list Guid of the user list.

The sourcecode for the file “AutocompleteForPeoplePicker.js” looks like this:

/* Add autocomplete functionality to a SharePoint people picker
 * -----------------------------
 * Created by Alexander Bautz
 * [email protected]
 * http://sharepointjavascript.wordpress.com
 * v1.0
 * LastMod: 24.03.2010
 * -----------------------------
 * Must include reference to jQuery 1.4, jQuery UI 1.8 and to the folloving scripts:
 * ----------------------------------------------------
 * interaction.js - http://spjslib.codeplex.com/
 * stringBuffer.js - http://spjslib.codeplex.com/
 * ----------------------------------------------------
*/

function peoplePickerAutoclomplete(FieldInternalName){
if(typeof(fields)=='undefined')fields = init_fields();

var myPicker = $(fields[FieldInternalName]);
if(myPicker.find('div.ms-inputuserfield:visible').length>0){
	var ie=true; // Internet Explorer
	var toFind = 'div.ms-inputuserfield';
	var inputStyle = "margin:-1 0 -1 0;height:18px;font-family:Verdana,sans-serif;font-size:8pt;width:100%;display:none";

}else{
	var ie=false; // Firefox
	var toFind = 'textarea:first';
	myPicker.find('textarea:first').css({'height':'18px'});
	var inputStyle = "margin:1 0 1 0;height:18px;font-family:Verdana,sans-serif;font-size:8pt;width:100%;display:none";
}
	myPicker.find(toFind)
		.before("<input hiddenval='' style='"+inputStyle+"' id='"+FieldInternalName+"'/>")
		.focus(function(){
			$(this).hide().prev().show().focus();
		});

	// Add autocomplete
	$("#"+FieldInternalName).autocomplete({
			source: allUsers,
			select: function(event, ui) {
				fillPicker(ie,myPicker,FieldInternalName,ui.item.writeBackValue,ui.item.value);
				return false;
			}
		}).blur(function(){
			var currVal = $(this).val();
			var prevVal = $(this).attr('hiddenval')
			if(currVal!=''&&currVal!=prevVal){
				$(this).val($(this).attr('hiddenval'))
			}else if(currVal==''){
				fillPicker(ie,myPicker,FieldInternalName,'','');
			}
			$(this).hide().next().show();
	});
}

function fillPicker(ie,field,fin,loginName,dispName){
	if(ie){
		// IE
		field.find('.ms-inputuserfield').html(loginName);
		$("#"+fin).val(dispName).attr('hiddenval',dispName);
		field.find('img:first').click();
	}else{
		// FF
		field.find("textarea:first").val(loginName);
		$("#"+fin).val(dispName).attr('hiddenval',dispName);
	}
}

function getUsers(userListBaseUrl,userListGuid){
	var query = "<Where><And><IsNotNull><FieldRef Name='EMail' /></IsNotNull>" +
				"<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq></And></Where>" +
				"<OrderBy><FieldRef Name='Title' Ascending='TRUE'/></OrderBy>";
	wsBaseUrl = userListBaseUrl + '/_vti_bin/';
	var res = queryItems(userListGuid,query,['ID','Title','Name','EMail','ContentType']);
    var ret = [];
    $.each(res.items,function(idx,item){
    	ret.push({label:item['Title']+"<br>"+item['EMail']+"<br>"+item['Name'],value:item['Title'],writeBackValue:item['Name'],desc:'Test'});
    });
    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;
}

Save as “AutocompleteForPeoplePicker.js”, mind the file extension, and upload to the script library as shown above.

I will update the article on Edit date, single line text, number or boolean columns directly in list view based on this script to allow setting a people picker field directly in a list view.

Ask is anything is unclear.

Regards

Alexander

This article was originally published on Alexander’s blog SharePoint JavaScripts.

Guest Author: Alexander Bautz
SharePoint JavaScripts

Alexander Bautz is a SharePoint consultant/developer (mainly JavaScript/jQuery solution) living in Norway. Alexander spends a lot of his spare time blogging on the same topics. His focus area is "end user customizations" with no (or as little as possible) server side code.

View all entries in this series: Alexander Bautz»
 

Please Join the Discussion

11 Responses to “Autocomplete for SharePoint people picker”
  1. Beckie White says:

    oooh I CANNOT wait to plug this in!

  2. Shalin Parmar says:

    Hi,

    Great post but I am curious to know what is the “User List” actually? Is it a list created by the users or some in-built list?

  3. Cool stuff as always Alexander!

  4. Serge says:

    Hi,

    The reference at the two parts codes do not work for me or I am not able to read the correctly.

    The scripts “interaction.js” and “stringBuffer.js” is created by Erucy and published on CodePlex.

    When I click on the link the page is empty and do not make any reference to the code at all.

  5. Bruno Graça says:

    Hi Alexander,

    This is not running for me . On the getUsers(userListBaseUrl,userListGuid) function when I put a alert(res.count) the result is -1, so I is not returning any value from the List, I suppose that the GUID is wrong but ever time I follow your suggestion to get the list GUID, give me the same result.
    Any suggestion?

  6. Bruno Graça says:

    Hi again Alexander,

    ok the last issue was suppress, however, now I have another issue. On the autocomplete.js all the test that I made it´s seems ok , but on CEWP the allUsers function return the data from the list, i call FieldInternalName on the peoplePickerAutoclomplete but does not make the autocomplete on my people picker, so I think that the error is on my FieldInternalName, because I didn´t find this expression by the way you suggest . By the way you suggest to find the internal error I not find any information. Do you have any suggestion again?

    Thanks for your attention

  7. Bruno Graça says:

    After I Debugged the CEWP code, the people picker is populate with garbage and give me label error like :”You are only allowed to enter one item.”

    Do you have any suggestion ?

    Cheers

Trackbacks

Check out what others are saying about this post...
  1. Free Flip HD Camcorder from Bamboo; Search Improved in SharePoint 2010; Office 2010 Standards FAIL…

    Top News Stories How Search Has Improved in SharePoint 2010 (CMSWire) In my last article we looked at…




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!