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?
Node
field values. By the way there's absolutely no reason to make another query when you have all the needed informations in theNode
itself which is the entity avalaible in the hook you're using.