1

I'm using the Group module.

How can I get the id of a group whose a user is a member (I have the user id)?

0

I would just start with creating a view (using Views) of all "Group memberships", and include all available colums of that specific base table. It should include things like "user id" and "group id".

If you then add a contextual filter to limit it to some selected user id, you'll get 1 views result (row) for each group that the selected user is member of, or is invited for, revoked from, etc (membership status for each group is one of the available columns to include in your view). For each group you'll have its group id available also, so if needed you can add a relationship to the group itself to have access to additional data about the group itself (eg: the group title, or any of its custom fields you added).

After you have such view created, you have a prototype of anything else you want to do with that, e.g use whatever you want in your custom module to invoke the Group's API functions.

PS: refer to my answer to "How to add a column to the list of group members or create a Views equivalent of it?" for getting started with creating such view (even though it's for D7, for D8 you can use a similar one).

0

Assuming you mean how to do this programmatically.

One thing to understand is that there are mid level entities between a user account and groups called GroupMembership entities.

There is a service called group.membership_loader that provides the utility functions for retrieving the membership entities:

  $group_memberships = \Drupal::service('group.membership_loader').loadByUser($account);

With a list of memberships, you can then load the groups:

  $groups = [];
  foreach ($group_memberships as $group_membership) {
    $groups[] = $group_membership->getGroup();
  }

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.