How to add user to a group using FieldUserValue
-
17-01-2021 - |
Domanda
I have a super annoying issue where this is the process:
- User fills in form
- My application uses CSOM to get a list of users from the form (these are selected by the user with people picker - I also want the
Author
) - I need to add these users to some groups, and here is the problem..
The ListItem
user fields are returning FieldUserValue
s rather than User
objects - and these don't contain the user's login name, so how am I supposed to add that user to a group?
It seems ridiculous that I have to write some query using the user's lookup ID, can't I just pass in the FieldUserValue
to a group creation method? The only way I have found is to pass in the UPN of the user.
Please can someone help it is so frustrating dealing with this system.
Soluzione
You can use the web.EnsureUser
method to get the user object. In the method, pass the LookupValue
.
Try and modify the below sample code:
FieldUserValue[] fuv = (FieldUserValue[])listItem["UserField"];
for (int i = 0; i < fuv.Length; i++)
{
User user = clientContext.Web.EnsureUser(fuv[i].LookupValue);
clientContext.Load(user);
clientContext.ExecuteQuery();
// code to add user to group
// get the group
var group = clientContext.Web.SiteGroups.GetByName("Group name");
group.Users.AddUser(user);
}
Altri suggerimenti
As Gautam mentioned, I can do this by using EnsureUser
However, what I came to realise was that my organisation seems to have 2 SharePoint instances - a 365 version as well as what I think is a on-premises version.
Therefore, before calling EnsureUser
I need to make sure that the ClientContext
is pointing at the correct instance.
e.g.
If I use ClientContext("OnPrem.Company.com")
, then the user's LoginName
is given as domain\user.name
, but if I use Clientcontext("Company.SharePoint.com")
, then the username is given as user.name@domain.com
, which is the actualy selection I want to use when adding the user to a group and when storing the username in the DB