0

I need the ID of the node the inserted comment is attached to. This is what I have tried:

function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{

   // According to https://drupal.stackexchange.com/questions/145823/how-do-i-get-the-current-node-id
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        $nid = $node->id();
    }
    drupal_set_message("The vaue is " . print_r($nid), 'warning');
}

But... The value I get is "1", while it should be (according to node URL) "55". Or am I using drupal_set_message for debugging the wrong way?

I also tried $entity->get('entity_id')->target_id (according to: How to get the node id the comment is attached to in hook_comment_insert?) or \Drupal::routeMatch()->getRawParameter('node'), but I always get "1" and I'm positive that the website cache has been cleared.

3
  • I saw that, but "$entity->get('entity_id')->value" gives me back "1" too.
    – CharlesM
    Jul 8 '19 at 14:42
  • Have you cleared cache?
    – user72672
    Jul 8 '19 at 14:42
  • Yes, I did clear cache
    – CharlesM
    Jul 8 '19 at 14:47
0

print_r($variable) does not return anything useful, it just outputs text (which it does successfully, so it returns boolean TRUE [which is rendered as 1 when printed]). Your drupal_set_message basically does something like echo ($string . $boolean . $string)

Use print_r($variable, true) to return the output of the print_r to the calling function, instead of rendering it.

See https://www.php.net/manual/function.print-r.php

0

Look here https://git.drupalcode.org/project/drupal/blob/8.8.x/core/modules/comment/src/Entity/Comment.php#L369 https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21Entity%21Comment.php/function/Comment%3A%3AgetCommentedEntity/8.2.x

and... =) How to get the node id the comment is attached to in hook_comment_insert?

1

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