To save a user name into a people field

3.2k views Asked by At

To save a user name into a people field:

Provided a people editor control in my custom form and saved each resolved entity as follows:

 if (currentPeopleEditor.Entities.Count != 0)
 {
 SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();
 for (int index = 0; index < currentPeopleEditor.ResolvedEntities.Count; index++)
 {
  PickerEntity ObjEntity = (PickerEntity)currentPeopleEditor.ResolvedEntities[index];
  userCollection.Add(new SPFieldUserValue(objSPWeb,Convert.ToInt32(ObjEntity.EntityData["SPUserID"]), ObjEntity.Key));
  }
  newItem[Field.Key.ToString()] = userCollection;
  }            

It was working very fine until some user stated getting this exception: "Invalid Look-up Value

A look-up field contains invalid data, Please check the value and try again."

On investigating we found that this error was occurring because ObjEntity.EntityData["SPUserID"]) was returning as null.

It was happening because the requirement is to save some users name who don't access this site collection but they are member of corporate AD system.

2

There are 2 answers

0
user669915 On BEST ANSWER

Long story short to resolve above problem in SharePoint 2010 just use web.EnsureUser()

It adds user to the all user list and returns spuser object.

0
user669915 On

To resolve this issue we looked up to SharePoint and replicated what they do. In one of the list add a column of type people and group allowed it to pick any user. create new item in this list and Pick a user whose name is not present in all users list. save the item. go back to all users list you will see that new user name got added to this list.

Note: To see all users list in UI browse to following location: site collection URL/_catalogs/users/simple.aspx

so now to achieve the same functionality. I updated the code as follows

if (currentPeopleEditor.Entities.Count != 0)
{
    SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();
    for (int index = 0; index < currentPeopleEditor.ResolvedEntities.Count; index++)
{
               PickerEntity ObjEntity = (PickerEntity)currentPeopleEditor.ResolvedEntities[index];
               if (ObjEntity.EntityData["SPUserID"] == null)

                {
                      SPContext.Current.Site.RootWeb.AllUsers.Add(ObjEntity.Key, ObjEntity.EntityData["Email"].ToString(), ObjEntity.DisplayText, "");

                     SPContext.Current.Site.RootWeb.Update();

                     userCollection.Add(new SPFieldUserValue(objSPWeb, Convert.ToInt32(SPContext.Current.Site.RootWeb.AllUsers[ObjEntity.Key].ID), ObjEntity.Key));
                      }
                      else    
                       {    userCollection.Add(new SPFieldUserValue(objSPWeb,                 Convert.ToInt32(ObjEntity.EntityData["SPUserID"]), ObjEntity.Key));
                       }
         }
    newItem[Field.Key.ToString()] = userCollection;
 }