Programmatically add new role to group member

Created on 27 March 2017, over 7 years ago
Updated 11 April 2023, about 1 year ago

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

πŸ’¬ Support request
Status

Closed: works as designed

Component

Documentation

Created by

πŸ‡³πŸ‡ΏNew Zealand jlscott

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

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

Production build 0.69.0 2024