1

I use the Group module and I have created several groups and assigned several nodes as content of these groups.

For example, I know id of some node. How can I figure out which groups contain this node ? That is, how to get group ids by nid, if this node is a content of these groups ? And I don't want to use SQL for it. Are there methods of classes for it ?

3 Answers 3

5

The way Group module maintainer recommended:

use Drupal\group\Entity\GroupContent;

function getGroupIdsByEntity($entity) {
  $group_ids = [];

  $group_contents = GroupContent::loadByEntity($entity);
  foreach ($group_contents as $group_content) {
    $group_ids[] = $group_content->getGroup()->id();
  }

  return $group_ids;
}
1
  • This is the best answer
    – sonfd
    Commented Oct 29, 2018 at 4:00
2

Try something like this: (gids will be your groups ids). I check the entity type because group content will also load the group members.

  $ids = \Drupal::entityQuery('group_content')
      ->condition('entity_id', $node->id())
      ->execute();

  $relations = \Drupal\group\Entity\GroupContent::loadMultiple($ids);

  foreach ($relations as $rel) {

    if ($rel->getEntity()->getEntityTypeId() == 'node') {

      $gids[] = $rel->getGroup()->id();
    }
  }
0

Another helpful function in this situation might be getContentByEntityId($plugin_id, $id); from GroupInterface.php. $plugin_id is the content enabler plugin ID to filter on and $id is your node id. However, you would need to loop through your groups and do $groupContentArray = $group->getContentByEntityId($plugin_id, $id) to get an array of GroupContentEntities (of your node) if they exist for this group.

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.