How to Use the PeopleEditor Control: Saving Data

The PeopleEditor control is a common control that you’ll find implemented throughout SharePoint. If you’re building any custom web parts or application pages, you may want users to enter people specific information. The PeopleEditor is a good choice, however, there isn’t much out there in terms of documenting it’s use. Hopefully the information below will help get you started. If you are having issues, or if there is something I’ve missed in my post, please feel free to leave me a comment.

NOTE: One thing I found was that in order for this control to successfully save a user, that user has to exist within the site collection. If they don’t exist, the web.SiteUsers call will fail with an exception ‘user cannot be found’.

UPDATE: You can use the EnsureUser method to verify that the specified user exists and is a valid user of the web site. The neat thing about this method is that it will add the user to the site if they do not already exist, thus making the SiteUsers call unnecessary. Keep in mind that if you do use this method, you may need to elevate permissions to make that call, as not all users have access to add other users to your site collection.

To get started, create a new Custom List named Demo. Within List Settings, create a column of type Person or Group named Managers.

In this particular example, I’ll be building a custom application page with a single PeopleEditor control and a submit button. Create a new page (or download the files I’ve prepared for this article here), called Demo.aspx and store it in the _layouts directory.

Since the people editor control is located within the Microsoft.SharePoint.WebControls namespace, you’ll have to register the tag prefix at the top of your page:

1
<%@ Register TagPrefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Insert the control on the page. If you look at my Demo.aspx page, I’ve put my control within a table tag, but you can format this however you’d like:

1
<wssawc:PeopleEditor AllowEmpty="false" Width="300px" id="peManagers" runat="server" SelectionSet="User" />

AllowEmtpy – let’s you specify if blank values are permitted for this control
SelectionSet – can be User or SecGroup or SPGroup or all three: User, SecGroup, SPGroup
MultiSelect – set to true or false, false if you don’t want the user to be able to select more than one

Insert an asp:Button control onto the page; we’ll use this to submit the people data to the list.

1
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" ValidationGroup="Main" Text="OK" CssClass="ms-ButtonHeightWidth" />

In order to save values from the control to the column we created, you’ll need the following code in the button submit event:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
protected void btnSubmit_Click(object sender, EventArgs e)
{
    // create a web object with context for the current site
 
    SPWeb web = SPContext.Current.Web;
 
    // get the entries that were entered into the people editor and store them in a string
 
    string managers = peManagers.CommaSeparatedAccounts;
 
    // commaseparatedaccounts returns entries that are comma separated. we want to split those up
 
    char[] splitter = { ',' };
 
    string[] splitPPData = managers.Split(splitter);
 
    // this collection will store the user values from the people editor which we'll eventually use
    // to populate the field in the list
 
    SPFieldUserValueCollection values = new SPFieldUserValueCollection();
 
    // for each item in our array, create a new sp user object given the loginname and add to our collection
 
    for (int i = 0; i < splitPPData.Length; i++)
    {
        string loginName = splitPPData[i];
 
        if (!string.IsNullOrEmpty(loginName))
        {
            SPUser user = web.SiteUsers[loginName];
 
            // you could also use SPUser user = web.EnsureUser(loginName);
 
            SPFieldUserValue fuv = new SPFieldUserValue(web, user.ID, user.LoginName);
 
            values.Add(fuv);
        }
 
    }
 
    // set the Person or Group column
 
    SPListItemCollection listItems = web.Lists["Demo"].Items;
 
    SPListItem manager = listItems.Add();
 
    manager["Managers"] = values;
 
    manager.Update();
}

That should do it. You should be able to save the entries to the list. If you’d like to learn how to read values from a list column into a PeopleEditor control, you can read that post here. Any feedback?

, ,

7 Responses to “How to Use the PeopleEditor Control: Saving Data”

  1. Paul December 8, 2008 at 6:11 pm #

    Quick question, have you found a good way to pre-populate a PeopleEditor with a validated entity? What I mean by this is, if you have a workflow and you enter two approvers (Approver A and Approver B) at the beginning, when ApproverA gets his task, he will see a PeopleEditor control pre-populated with ApproverB, which he would be able to change if he wants. Make sense? Any help you could offer would be appreciated.”

  2. Paul December 8, 2008 at 6:11 pm #

    Nevermind… this page says how to do that… http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.portal.webcontrols.itempicker.validateentity.aspx

  3. Gitolekha December 8, 2008 at 6:12 pm #

    I have a tab control in which I have a peopleeditor in the first tab called “pplowner”. The last tab is a summary of values of controls selected in the other tabs. I have to do this using javascript. currently, I am doing, var elem = document.forms[0].elements; for(var i=0; i < elem.length; i++) { if(elem[i].id.indexOf(“pplOwner”) != -1 && elem[i].id.indexOf(“TextBox”) != -1) users = elem[i].value; } Now, I display the value in users in a label. The poblem that I am facing is, if I delete a value from the peopleeditor’s textbox, I still get the old values in users. Also, the names are displayed as domain/userid, whereas I want it as user’s name as it is shown in the peopleeditor. Can you suggest a solution?

  4. JP April 21, 2014 at 5:52 pm #

    Hi, Do you know if I can use the PeopleEditor in a non-SharePoint(ex: ASP.Net/MVC) if I add a reference to Microsoft.SharePoint.DLL? I tried that and got the below error. Any help will be appreciated.

    [NullReferenceException: Object reference not set to an instance of an object.]
    Microsoft.SharePoint.WebControls.EntityEditor.IsV4Plus() +43
    Microsoft.SharePoint.WebControls.EntityEditor..ctor() +271
    Microsoft.SharePoint.WebControls.EntityEditorWithPicker..ctor() +245
    Microsoft.SharePoint.WebControls.PeopleEditor..ctor() +285

  5. Shereen Qumsieh April 28, 2014 at 5:32 pm #

    Hi JP, not too sure, as I’ve never tried this. Did you ever find a resolution?

  6. Soumyadev Bhattacharyya September 9, 2014 at 11:15 pm #

    Hi,
    Thanks for coming up with this nice article.

    We have also written a similar code to get users from saved DB and during page load set them to client people picker control

    However, sometime we are seeing that the ID is not getting resolved as expected and the entire SAML token with user ID gets displayed on the people picker control

    the sample code which adds users to List

    PickerEntity entity = new PickerEntity();
    PeopleEditor pe = new PeopleEditor();
    entity.EntityData[“AccountName”] = userProfile.AccountName;//oSPUser.LoginName;
    entity.EntityData[“SPUserID”] = userProfile.ID;//oSPUser.ID;
    entity.EntityData[“Email”] = userProfile[PropertyConstants.WorkEmail].Value;//oSPUser.Email;
    entity.Key = userProfile.AccountName;
    entity.Description = userProfile.AccountName;
    entity.DisplayText = userProfile.DisplayName;
    entity = pe.ValidateEntity(entity);

    if (entity != null)
    {
    entity.IsResolved = true;
    savedEntity.Add(entity);

    Logger.LogError(SPCustomCategory.RequestForm.ToString(),
    string.Format(“Entity object resolved in People editor {0}”, userProfile.AccountName));
    }
    else
    {
    entity.IsResolved = true;
    savedEntity.Add(entity);

    Logger.LogError(SPCustomCategory.RequestForm.ToString(),
    string.Format(“Entity object not resolved in People editor {0}”, userProfile.AccountName));
    }

  7. srikanth April 27, 2016 at 10:19 am #

    thank u somuch.. it works for me

Leave a Reply