Friday, 13 May 2011

Adding / Appending spuser in people picker using object model

We were having the requirement to add a user to existing set of user in people type of fields using the object model. 

Following code we have used to add/append a user with existing user in people type fields.

bool bUserExists = false;
SPWeb web = SPContext.Current.Web;
SPFieldUserValueCollection spFieldUserValue = null;
web.AllowUnsafeUpdates = true;
//Get the list item
SPListItem objListItem = web.Lists["Mylist"].GetItemById(1);

// Check if there is any value in MyExitingUser of the splist item field
if (objListItem["MyExitingUser"] != null)
{
spFieldUserValue= new SPFieldUserValueCollection(web, Convert.ToString(objListItem["MyExitingUser"]));
}
else
{
spFieldUserValue = new SPFieldUserValueCollection();
}

// Check if the user we are going to add already exist or not
foreach (SPFieldUserValue fieldVale in spFieldUserValue)
{
if (fieldVale.LookupValue == sUserName)
bUserExists = true;
}
// If user does't exist then add the existing user group.
if (!bUserExists)
{
      //Get the spuser object for the current user
      SPUser objUserContributor = web.AllUsers[sUserName];

      // Add create the SPFieldUserValue object for the current user
      SPFieldUserValue objContributor = new SPFieldUserValue(web, objUserContributor.ID, objUserContributor.LoginName);

// Add to the people collection of existing user
      spFieldUserValue.Add(objContributor);

      // Set the splist item with the updated values
      objListItem["MyExitingUser"] = spFieldUserValue.ToString();

      // Update the list item
      objListItem.Update();

      web.AllowUnsafeUpdates = false;
}t