2

Using Drupal 8 with the Group module, I have an action that is run via hook_node_insert that needs to know the group id of the group that the node is added to.

Im using this code to get the group id of the group(s) that the node is a member of:

function get_groups_from_node($nid) {
  $group_ids = array();
  $ids = \Drupal::entityQuery('group_content')
    ->condition('entity_id', $nid)
    ->execute();

  $relations = \Drupal\group\Entity\GroupContent::loadMultiple($ids);
  foreach ($relations as $rel) {
    if ($rel->getEntity()->getEntityTypeId() == 'node') {
      $group_ids[] = $rel->getGroup()->id();      
    }
  }
  
  return $group_ids;
}

When I feed the nid of an existing group node into the function, it works, but not for the newly created ones that are cought by the hook.

function mymodule_hook_node_insert (NodeInterface $node) {     
  
  $nid = $node->nid->value;  
  $groups = get_groups_from_node($nid);

}

The information does not seem to be available at the time of node creation - I guess the hook fires before the node is actually added to a group?

Should I use another hook, or is there a better way?

10
  • Does it throw an error?
    – No Sssweat
    Commented Oct 30, 2020 at 19:11
  • no, it just returns NULL. if i run the function on the same node manually later, it returns the groupid.
    – stemiwe
    Commented Oct 30, 2020 at 23:51
  • Take the hook out of the function name and clear cache. Does $node->id() also return null?
    – Kevin
    Commented Oct 31, 2020 at 0:10
  • no, node->nid->value returns its value just fine what do you mean "take the hook out"? I don't understand - then the function would not run, no?
    – stemiwe
    Commented Oct 31, 2020 at 8:25
  • 1
    Yep it's not the problem but since your entity query which "works just fine" doesn't work on node creation, you should better dig into the Node field values. By the way there's absolutely no reason to make another query when you have all the needed informations in the Node itself which is the entity avalaible in the hook you're using.
    – MacSim
    Commented Oct 31, 2020 at 15:14

0

Your Answer

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

Browse other questions tagged or ask your own question.