Reputation: 129
This question is related to Drupal 8 Group module, https://www.drupal.org/project/group
I am stuck and need help with how to programmatically add a user to a group with a particular role. I am trying to assign a user to a group and role via a feed import but unable to figure out how. To elaborate, let's say we have two groups DEV and QA. DEV is of group type A and QA is of group type B. Both groups type A & B have roles X, Y and Z (group roles). Now, I have a user $account and I want it to get added to say group QA with role Y. Can someone help and state a way I can achieve this programmatically? Code examples/snippets will be extra helpful.
Upvotes: 0
Views: 1678
Reputation: 51
Some OLD code here that may help. Had to dig it out of git, deleted a couple of years ago as no longer needed by the project. May be deprecated!
You are loading up the group and using the $group->addMember() function. I have just added the member but you can add a second param that is an associative array that can indicate roles to add to.
$new_user = \Drupal\user\Entity\User::load($some_user_id);
// Get the group entity.
$gid = $form_state->getValue('gid');
$group = \Drupal::entityTypeManager()
->getStorage('group')
->load($gid);
// Add user as a member of the group.
$group->addMember($new_user);
// Set the owner of the group to be the user.
$group->set('uid', $new_user_id);
// Save changes to group. Anything below here should only be changes to
// Group Content.
$group->save();
$tags = $group->getCacheTagsToInvalidate();
Cache::invalidateTags($tags);
Upvotes: 2