Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Trying to update a group membership to add an additional role, but cannot find any help on how to do this.
I want to add the role of "manager" to all owners of "client" type groups, using the following code:
// Get the group owner
$owner = $group->getOwner();
// Get the membership details of the owner
$membership = $group->getMember($owner);
// Get the roles of the owner
$roles = $membership->getRoles();
// Check whether the owner has manager role
if (!isset($roles['client-manager'])) {
// No, so add the manager role to the membership
// >>> The following doesn't work, but trying to get the idea <<<
$manager = new GroupRole();
$membership->addRole($manager);
$membership->save();
}
Any help or advice appreciated
Comments
Comment #2
jlscott CreditAttribution: jlscott as a volunteer commentedComment #3
jlscott CreditAttribution: jlscott as a volunteer commentedI was eventually able to find the correct process. The working code follows:
Comment #4
jlscott CreditAttribution: jlscott as a volunteer commentedComment #5
jyothsnamu CreditAttribution: jyothsnamu as a volunteer commentedI was able to achieve this by following
$group_content = $membership->getGroupContent();
$existing_group_roles = $group_content->get('group_roles')->getValue();
foreach ($selected_roles as $selected_role) {
$existing_group_roles[] = ['target_id' => $selected_role];
}
$group_content->get('group_roles')->setValue($existing_group_roles);
// Save updated entity
$group_content->save();
Comment #6
jyothsnamu CreditAttribution: jyothsnamu as a volunteer commented