Hi,
I am working on a project using Group module. I need to assign a group role to a member programmatically.

I could figure out to get the group roles of a membership using loadByUserGroup() of group role storage class. But I am kind of lost in finding a way to set additional roles. Couldn't figure out an appropriate setter method.

I am pretty new to drupal.org, just learning things the hard way & enjoying it :-). I hope I am asking this question in the right forum.

Hope to find some guidance soon.

Thank you.

Comments

JacobCF’s picture

I am able to add a member to a group using
$group->addMember($account, $values);
But I am not able to add any roles. Sadly, I am stuck at this point.

JacobCF’s picture

Go through this link https://www.drupal.org/node/2839968.

$group = Group::load($id), $id is the id of the group

taitai’s picture

I can add new members to the group using $group->addMember but can not set the $values parameter to include a role for the new member.
The member is added but without any roles.
Any help in setting the $values array will be appreciated.

JacobCF’s picture

To add a role you have to define the $values array like this

$roles = array('role1', 'role2');
$values = ['group_roles' => $roles];

taitai’s picture

Many thanks

midhunps’s picture

As I couldn't find a solution soon enough, I had used some other logic to work around the situation.

But sure, many thanks for the guidance, very much useful in future!

Thank you.

RaSpirit’s picture

This answer actually works and does the work