3

I am trying add members to a group programmatically using Groups module in Drupal 8, and I am doing the following to achieve this:

use Drupal\Core\Entity\ContentEntityBase;
$roles = array('test_role');
$values = ['group_roles' => $roles, 'gid' => 1];
$account = $this->createUser();
$group = \Drupal\group\Entity\Group::load(1);
$group->addMember($account, $values);

So, users are already present in the site. I want to add only those users to a group who have successfully paid for it. Hence, I am trying to write a custom solution that I add a user to an already existing group on the site. I came across this addMember($account, $values) function in the group module, however am still not sure on what values its arguments ($account and $values) take. Above piece of code does not add users to my group. Can someone please suggest what wrong I am doing here?

  • Please explain what is not working, that helps us answer you. From the looks, you are not saving the created user. Try to add ->save(); after createUser() – Neograph734 Jun 22 '17 at 14:16
  • Hi @Neograph734, Thanks for your response. I have edited my question above. I hope I have made it a little more clear. adding ->save() after createUser() doesn't seem to solve this. Can you please suggest something more on this? Thank you very much. – ekta Jun 22 '17 at 15:03
  • If users already exist, why do you create a user? ($account = $this->createUser();) Can't you load an existing user instead: $account = \Drupal\group\Entity\User::load(1);? – Neograph734 Jun 22 '17 at 15:12
  • Yes that is right actually. I am now loading an existing user and passing that as an argument in addMember function. However still it does not add the user to the group. – ekta Jun 22 '17 at 15:33
  • I am sorry, I don't see anything else... What if you remove the gid from $values? You should not have to set that anyway. Maybe someone else has a good insight. – Neograph734 Jun 22 '17 at 15:44
4

So, modifying the code a little bit and saving the group after adding member to it worked for me. Pasting the updated code below:

use Drupal\Core\Entity\ContentEntityBase;
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$group = \Drupal\group\Entity\Group::load($group_id);
$group->addMember($account);
$group->save();
| improve this answer | |
2

Without 'gid' code below works for me:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$group = \Drupal::entityTypeManager()->getStorage('group')->load(127);
$group->addMember($user, ['group_roles' => ['podrazdelenie-admin']]);
$group->save();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.