Thursday, October 27, 2011

PeopleEditor To SPFieldUserValueCollection

OBJECTIVE
To programmatically copy people selected from an asp.net People Editor to a SPFieldUserValueCollection field.

SPECIFICATION
The People Editor can contain multiple people, and allow Users and Groups selection.

SOLUTION
// myPeopleEditor is a PeopleEditor object in my asp.net form.

..
Item[“MyUserField”] = GetPeople(myPeopleEditor, Web);
..


private SPFieldUserValueCollection GetPeople(PeopleEditor people, SPWeb web)
{
  SPFieldUserValueCollection values = new SPFieldUserValueCollection();
  if (people.ResolvedEntities.Count > 0)
  {
    for (int counter = 0; counter < people.ResolvedEntities.Count; counter++)
    {
        PickerEntity user = (PickerEntity)people.ResolvedEntities[counter];
        switch ((string)user.EntityData["PrincipalType"])
        {
          case "User":
            SPUser webUser = web.EnsureUser(user.Key);
            SPFieldUserValue userValue = new SPFieldUserValue(web, webUser.ID, webUser.Name);
            values.Add(userValue);
          break;
 
          case "SharePointGroup":
            SPGroup siteGroup = web.SiteGroups[user.EntityData["AccountName"].ToString()];
            SPFieldUserValue groupValue = new SPFieldUserValue(web, siteGroup.ID, siteGroup.Name);
            values.Add(groupValue);                       
          break;
        }
      }
    }
    return values;
  }