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

jlscott created an issue. See original summary.

jlscott’s picture

Version: 8.x-1.0-alpha7 » 8.x-1.0-beta5
jlscott’s picture

I was eventually able to find the correct process. The working code follows:

// 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
  // Get the group_content entity
  $group_content = $membership->getGroupContent();
  // Set target group role
  $group_content->group_roles->target_id = 'client-manager';
  // Save updated entity
  $group_content->save();
}
jlscott’s picture

Status: Active » Closed (works as designed)
jyothsnamu’s picture

I 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();

jyothsnamu’s picture