stephenl
stephenl

Reputation: 3129

Add users to UserMulti field type using Client Object Model

I'm bit of a SharePoint noobie so please bear with me.

I need to be able to create a new list item in one our custom list using the client object model. I have been following the example described on the MSDN site and for the most part this has worked.

We have a list that contains several fields including a UserMulti field type. I am having problems adding users to this field. So far I have tried the following but this somehow always seems to default to the system account rather than the user specified in the field.

   ...
   listItem["ProjectMembers"] = "1;#domain\\johndoe";
   listItem.Update();
   _clientContext.ExecuteQuery();

Do I need to do some type of lookup first? Any help is appreciated. Thanks.

Upvotes: 3

Views: 6003

Answers (2)

Dan
Dan

Reputation: 16

Microsoft has a wiki article, "SharePoint: A Complete Guide to Getting and Setting Fields using C#" that can help. http://social.technet.microsoft.com/wiki/contents/articles/21801.sharepoint-a-complete-guide-to-getting-and-setting-fields-using-c.aspx#Set_and_Get_a_Multi-Person_Field

It includes this sample code.

var lotsofpeople = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
var personA = web.EnsureUser("contoso\\fred");
var personAValue = new SPFieldUserValue(web, personA.ID, personA.LoginName);
var personB = web.EnsureUser("contoso\\barnie");
var personBValue = new SPFieldUserValue(web, personB.ID, personB.LoginName);
lotsofpeople.Add(personAValue);
lotsofpeople.Add(personBValue);
item["lotsofpeoplefield"] = lotsofpeople;
item.Update();

Upvotes: 0

stephenl
stephenl

Reputation: 3129

It took a little while but I figured it out in the end. Below are two approaches you can take

  1. Assign a Principal to the list item

        var principal = _rootWeb.EnsureUser("domain\\johndoe") as Principal;
        listItem["ProjectMembers"] = principal;
        listItem.Update();
        _clientContext.ExecuteQuery();
    
  2. Assign an list of FieldUserValue if you need to assign more than one user to the field.

        string[] users = { "domain\\johndoe", "domain\\peterpan" };
        var projectMembers = users
            .Select(loginName => FieldUserValue.FromUser(loginName))
            .ToList();
    
        listItem["ProjectMembers"] = projectMembers;
        listItem.Update();
        _clientContext.ExecuteQuery();
    

I'm sure there's better ways of doing things and you could combine the two to ensure that the users are valid before adding them to the list, but this is working so far. Hope this help someone else.

Upvotes: 6

Related Questions