Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
stephenl Avatar asked Apr 14 '26 06:04

stephenl


1 Answers

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.

like image 104
stephenl Avatar answered Apr 16 '26 05:04

stephenl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!