Quick Tip: Using the SharePoint ‘Person or Group’ field in code
One of the coolest types of site column (or field) in SharePoint is the ‘Person or Group’ field type. This allows you to select people from the GAL using a nice little picker control. When users are selected, you benefit from all of the presence capabilities of SharePoint as shown in this screen shot:
I recently had to programmatically add users to one of these ‘person or group’ fields where I only had the Login Name (domain\user) of the user I was adding as an input. It took me a while to work out how to populate a ‘Person or Group’ field from code so I thought I’d share my findings. It is worth noting that my esteemed co-workers Nigel Bridport and Pete Mellish both helped with figuring out the right format for this.
In order to populate these fields, you need a very specific combination of the User ID (see below for how to get this), their full Login Name (domain\user) and some magic characters (;#). The actual formula is as follows
<UserID>;#<UserLoginName>
for example
10;#europe\mkearn
In actual fact, I found that if you are only entering one person, you only need the User ID, but I think it is best to add the alias if you can. If you wish to add multiple people it is the same formula but the different people are separated by ;# as shown below
<UserID1>;#<UserLoginName1>;#<UserID2>;#<UserLoginName2>;#<UserID3>;#<UserLoginName3>
for example
10;#europe\mkearn;#3;#europe\ashleyy;#12europe\johnc
Word of warning ….If you wish to add your ‘Multiple Person or Group’ field via a Feature or Site Definition, there are some key things you need to know about Multiple User fields. See George Bonney’s great article which give you all of the details on how to do this.
So now we have the right formula, how do we actually use it?
The UserID relates to the ID of the user within the site collection. This is fine but the chances are that not all users are members of the site collection. To address this, the SharePoint OM has a handy little method called SPWeb.EnsureUser() which accepts a Login Name of a user as a string and first checks if the user exists in the site collection, if it does not then it adds the user and returns an SPUser object. Please be aware that you may need to set SPWeb.AllowUnsafeUpdates = True for this to work.
From the SPUser object it is very simple to get the ID (SPUser.ID.ToString() and SPUser.LoginName.ToString() ) and then use simple string building to get the string in the right format for the ‘Person or Group’ field.
The following code is a simple example of a Console Application which accepts a semi-colon delimited list of aliases (i.e. domain\user;domain\user;domain\user) and then adds them to a ‘Person or Group’ field called ‘MyPersonField’ in a list.
You can add this to the Main method of a Console Application and so long as you add the necessary references to SharePoint dlls (and the right using statements) it will work if you execute it on a SharePoint server (be sure to change the values of site, list and the name of the ‘MyPerson’ field to match your setup).
Console.WriteLine("Enter a ; delimited list of domain\alias that need to be added:");
string sAliases = Console.ReadLine(); //captures whatever the user entered
string sValueToAddToFieldInSP = ""; //used to build the full string needed for the person field
string sAllContacts = "";
using (SPSite site = new SPSite(“https://sites/site/yoursite”))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
string[] aAliases = sAliases.Split(';');
foreach (string sAlias in aAliases)
{
SPUser user = web.EnsureUser(sAlias);
sAllContacts += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
}
web.Update();
}
}
if (sAllContacts.EndsWith(";#"))
{
sAllContacts = sAllContacts.Substring(0, sAllContacts.Length - 2);
}
//add the list item
SPList l = web.Lists["<name of your list>"];
SPListItem li= l.Items.Add();
li["Title"] = sAllContacts ;
li["MyPerson"] = sAllContacts ;
li.Update();
Console.WriteLine("Done");
Using the InfoPath Contact Selector Control
One of the main places where you might use the technique described in this article is in an InfoPath where you wish to use the users selected in a Contact Selector control and promote them to SharePoint as a ‘Person or Group’. Unfortunately, this is not quite as simple as it should be because InfoPath does not natively understand the ‘Person or Group’ field type in SharePoint so you cannot directly promote it via property promotion.
The explanation of how you might do this in InfoPath is too lengthy for this article so watch this space for a follow-up coming soon!!
That is the end of the article, I hope you found it useful.
This article was published by
Martin Kearn Senior Consultant Microsoft Consulting Services UK Martin.Kearn@Microsoft.com |
Comments
Anonymous
February 16, 2009
PingBack from http://www.anith.com/?p=10525Anonymous
February 17, 2009
Rather than mess with ";#", you can use the SPFieldUserValue and SPFieldUserValueCollection classes, extended versions of SPFieldLookupValue and SPFieldLookupValueCollection. Cheers ~ KeithAnonymous
March 02, 2009
Siguiendo con la tradición, una vez más os presentamos el clásico recopilatorio de recursos, enlacesAnonymous
March 03, 2009
Please update this very useful item with details on how to implement this with the InfoPath Contact Selector Control...this is exactly how I need to be able to add/remove users into a pre-defined SharePoint group.Anonymous
March 11, 2009
Hi, is it possible to group persons using the 'person or group' field? I have a callendar, and a field INVITED (person or group), and I'd like to create a view where any person can see where are his/her meetings.Anonymous
March 29, 2009
Responidng to the comments left.
- Good point about the SPFieldUservalueCollection. I will look into that and update the article.
- Part 2 will be coming in the next few weeks. I've been very busy on a project and not got round to writing the article just yet - I will do though - promise!!!
- I do not believe you can group people in the type of field. You can have multiple 'people' which can be users or groups. To creat ethe view you mentioned, you just need to do a view where 'Invited' contains [Me] or osmething along those lines. Not tried this though so could be wrong.
Anonymous
April 16, 2009
Some time ago now, I published a post entitled Quick Tip: Using the SharePoint ‘Person or Group’ fieldAnonymous
May 27, 2009
Has anyone tried inserting a List Item with a "Person or Group" field using the SharePoint Web Service?Anonymous
June 22, 2009
Thank you thank you thank you. I have been pulling my hair out trying to get that field populated, and you have explained it perfectly. Thank you.Anonymous
October 06, 2009
You are an absolute life saver. Thanks so much for sharing!Anonymous
October 07, 2009
The comment has been removedAnonymous
December 30, 2009
here is my code: SPUser user = elevatedWeb.EnsureUser(userName); string sAllContacts = ""; sAllContacts += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#"; elevatedWeb.Update(); if (sAllContacts.EndsWith(";#")) { sAllContacts = sAllContacts.Substring(0, sAllContacts.Length - 2); } SPListItem item = AddlisItem.Items.Add(); item["Title"] = txtCompany.Text; item["user"] = sAllContacts; after the above line it throws :"value does not fall within the expected range" any solution......Anonymous
January 12, 2010
Thanks - this was very helpful!Anonymous
January 28, 2010
My questions or my problem. have formulary in infopath, and changed the content of formulary, public the formulary, add and activate en sharepoint central, but the formulary not changed. What is then problems and have the solutionsAnonymous
July 05, 2011
How to achieve the same using a web-service. Any help in this regard is appreciated.Anonymous
August 15, 2011
Hello! Nice article. I worked with EnsureUser and found out that there are a few other inconveniences. For example, we need almost always to use elevated privileges to deal with EnsureUser, otherwise exception will be thrown. Or for example, if user doesn't exist in user collection, it will be tried to add to this collection, but this means that spWeb object will be modified and it's required AllowUnsafeUpdates = true. Eventually, I've developed a small method-wrapper for EnsureUser. It's shown in my blog - <a href="dotnetfollower.com/.../a> Thanks!Anonymous
February 20, 2012
Did you ever write the sequal article on how to use this with InfoPath? I have forms I designed in infopath using the contact selector and I really need to be able to have those fields promote properly to person or group columns in SharePoint. I would LOVE to read the solution!Anonymous
May 13, 2012
Just thought of telling you to change your photo, you look scary, eyes wide popped out,Anonymous
June 06, 2012
Hi, Did you ever write the sequal article on how to use this with InfoPath?Anonymous
November 12, 2014
Hi Its good that we were able to set a user to people or group field. But how to set a SharePoint group to the people or group Field. If both the user id and group id are same what will be the result?? Kindly Share your work around for thisAnonymous
November 20, 2014
Awesome solution, it worked like a magic. I was struggling to add more than one contact to the people and group field through a custom web part and this solution worked like a charm. Thanks very much for posting it.