Skip to main content

ClientPeoplePicker in SharePoint 2013


Start using SharePoint 2013 I noticed that the way for selecting people or groups is changed.
The new way is simple – just ‘Enter name or email address’ without any icons for ‘Check Names’ or ‘Browse’. I guess that the PeoplePicker is changed but NO. PeoplePicker sitll has the same functionality as before.
There is a new control called ClientPeoplePicker.

How to use it:
1. Add this references

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

2. Add the following control declaration


      <wssawc:ClientPeoplePicker
        Required="true"
        ValidationEnabled="true"
        ID="peoplePicker"
        runat="server"
        InitialHelpText="<%$Resources:wss,aclinv_PickerIntialHelperText%>"
        VisibleSuggestions="3"
        Rows="1"
        AllowMultipleEntities="false"
        CssClass="ms-long ms-spellcheck-true" />


3. Form server side:
      a. Set SPUser to the control

SPUser assignToUser = GetYourSPUser();
if (assignToUser != null)
{
  PeopleEditor pe = new PeopleEditor();
  PickerEntity entity = new PickerEntity();
  entity.Key = assignToUser.LoginName;
  entity = pe.ValidateEntity(entity);
  entity.IsResolved = true;
  peoplePicker.AddEntities(new List<PickerEntity> { entity });
}
     b. Get selected user
SPUser user = null;
ArrayList resolvedEntities = peoplePicker.ResolvedEntities;
foreach (PickerEntity entity in resolvedEntities)
{
   string loginName = entity.Key;
   user = site.RootWeb.EnsureUser(loginName);
   break;
   // the picker in my sample is in single mode!
}

I developed this code reviewing the mngsiteadmin.aspx - the page for editing Site Collection Administrator. As a rule - always choose the simplest pages from the SharePoint default functionality for reverse enginiring.

Comments

  1. Great Article!
    A quick question..
    Do you know how to validate( to make this control a required field) this control on click of a button?

    ReplyDelete
    Replies
    1. Hi,
      To make the control required you should:
      1. Add Required="true" in the markup
      2. Validate onj the server in the following way:

      protected void btnSave_Click(Object sender, EventArgs e)
      {
      peoplePicker.Validate();
      if (peoplePicker.IsValid)
      {
      // the control has a value
      }
      }

      Delete
  2. Hi Dimcho,
    How can you disable the people picker, Enabled=false does not do the trick :)

    ReplyDelete
    Replies
    1. Hi,
      It seems the only way to do it is using javascript.
      Server side I was not able to make it.

      Delete
  3. Hi...

    I followed your steps.. Once I performed the.. 'Add the following control declaration'.

    I started getting the following errors..

    The name 'InitializeControl' does not exist in the current context.
    The name 'peoplePicker' does not exist in the current context.

    Im trying to add the control into a visual webpart.

    ReplyDelete
  4. Is it possible to write a custom FieldType with ParentType User that shows a ClientPeoplePicker instead of the old PeopleEditor Control? How does SharePoint wrap the Controls in each other?

    ReplyDelete
  5. How can i clear resolved entities

    ReplyDelete
    Replies
    1. Hi Shujaath Khan,
      I don't find a way to clear the Entities collection on post back.
      A workaround I can suggest is: instead of trying to clear the entities if they don't match your business rules, just mark them as not valid and leave the user to delete them:
      protected void Button1_Click(object sender, EventArgs e)
      {
      bool processEvent = true;
      peoplePicker.Validate();
      if (peoplePicker.IsValid)
      {
      SPUser user = null;
      ArrayList resolvedEntities = peoplePicker.ResolvedEntities;
      foreach (PickerEntity entity in resolvedEntities)
      {
      string loginName = entity.Key;
      user = SPContext.Current.Site.RootWeb.EnsureUser(loginName);

      // your logic here ....
      //if the user is not correct accordint to your business logic
      entity.IsResolved = false;
      processEvent = false;
      }
      }
      if (processEvent)
      {
      //Button1 logic ....
      }
      }
      Another way is to inherit the ClientPeoplePicker and overwrite the Validate() method by adding similar logic

      Delete
  6. 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));
    }

    ReplyDelete
  7. 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));
    }

    ReplyDelete
  8. 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));
    }

    ReplyDelete
    Replies
    1. Hi,
      In my code I use the SPClaimProviderManager.Local.ConvertClaimToIdentifier when I want to have the ‘clear’ login name. For example:
      PickerEntity pickerEntity = new PickerEntity()
      {
      Key = SPClaimProviderManager.Local.ConvertClaimToIdentifier(sPFieldUserValue.User.LoginName)
      };

      Try adding this in you code.

      Delete
  9. Hi I am facing one issue with this SP Client People Picker..Please help me out to resolve this issue. I have posted in msdn. Please go to:

    https://social.msdn.microsoft.com/Forums/office/en-US/0cd0cc35-3fe6-4638-b3eb-545ee0b2a33b/sharepoint-2013-client-people-picker-enter-key-press-issue?forum=sharepointdevelopment#0cd0cc35-3fe6-4638-b3eb-545ee0b2a33b

    ReplyDelete
  10. Hi sorry for posting on the post. i am required to do a form where the user will use the people picker to assign group members to the group. i would like to check how do i save the entries into my SQL DB such that it will ease me populating these values back when user want to edit the form. i have also posted this question on MSDN forum

    https://goo.gl/HxvHr4

    ReplyDelete

Post a Comment

Popular posts from this blog

SharePoint and List Joins with CAML

This came to me as an issue when I started migrating one project from SharePoint 2010 to SharePoint 2013. The code uses LINQ to SharePoint and it was not written in a clever way. We decide to use CAML queries and optimize the code. The scenario: Create gridview that gathers information from three(or more) lists. The problem: How to create the CAML query joins and projected fields correctly. Explanation : Option 1: Get generated CAML query from LINQ to SharePoint code This doesn’t work. I wrote the LINQ to SharePoint code connected the three lists. When I executed the code the following error was thrown – “ The query uses unsupported elements, such as references to more than one list, or the projection of a complete entity by using EntityRef/EntitySet. ” Here is some explanation about it and why this can’t be used. Option 2: Write the query yourself I found this article in MSDN . Read it ! The second part in it is exactly my scenario. But it takes me a lot of time to un...

Error: A duplicate field name "xxxx" was found

Soon I have some experience with migrating solution from SharePoint 2010 to SharePoint 2013. The migration was on 3 steps. First one was just to copy the custom fields, content types and list definitions from the old VS 2010 project into a new VS 2012 project for SharePoint 2013. Looks like pretty simple task but ….. The problem:  Error “ A duplicate field name "xxxx" was found ” when the feature for provisioning the fields and content types is activated. The solution: Review the field definitions and make sure no field has Name property equal to some of the ‘reserved’ values. Explanations: In SharePoint 2010 there was no problem to have these fields as a definition of custom fields: < Field     Type = " Note "     ID = " {893FB9BC-2DA4-4451-A1D1-88010CDC6A08} "     Name = " Description "     StaticName = " Description "     DisplayName = " Description 1 "     Requi...