0

What is the best way to make a hook that only fires when new members are added to a group?

I have a function that exports group memberships to moodle course enrolments. Right now I have it bound to _user_presave:

function mymodule_user_presave (User $user) {

  // Gather data.
  $userid = $user->id();
  $group_memberships = \Drupal::service('group.membership_loader')->loadByUser($user);
  foreach ($group_memberships as $group_membership) {
    $group = $group_membership->getGroup();
    $groupid = $group->id->value;
    $roles = $group_membership->getRoles();
    // Get roles.
    foreach ($roles as $rolename => $value) {

I bound it to user_presave after I realized that adding members to a group also calls this hook. But this seems unnecessarily inefficient, since it always returns all group memberships of the user, instead of just the latest one.

Is there a way to detect a new GroupMembership directly and hook into that?

1 Answer 1

0

this works:

function tm_mymodule_group_content_presave(Drupal\group\Entity\GroupContent $entity) {
  $group_content_type = $entity->getGroupContentType();
  if ($group_content_type->get('content_plugin') == 'group_membership') {    
    $groupid = $entity->gid->getValue()[0]['target_id'];
    $userid = $entity->entity_id->getValue()[0]['target_id'];
    $group = \Drupal::entityTypeManager()->getStorage('group')->load($groupid);
    $user = \Drupal::entityTypeManager()->getStorage('user')->load($userid);
    $membership = $group->getMember($user);
    $roles = $membership->getRoles();

     // Do something
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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