web-dev-qa-db-ja.com

hook_comment_insertでコメントが添付されているノードIDを取得するにはどうすればよいですか?

ノードを取得するにはどうすればよいですかidコメントが添付されているhook_comment_insert

私は次のコードを試しました:

function mymodule_comment_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'comment_custom' && $entity->get('entity_type')->value == 'node') {

    // Below returns empty, because "$entity->get('entity_id')->value" is empty.
    $node = Node::load($entity->get('entity_id')->value);

    // No luck with this one too.
    $node = \Drupal::routeMatch()->getParameter('node');

  }
}
6
D34dman

nidをロードする正しい方法は、

$entity->get('entity_id')->target_id

ではなく

$entity->get('entity_id')->value

どのキーを使用するか疑問がある場合は、

試して、

$entity->get('entity_id')->getValue()

戻り値を調べます。

5
D34dman

これは、この質問の重複としてフラグが付けられた別の質問に基づく遅い回答です。

Commentエンティティには、関連付けられているエンティティを取得するための便利なメソッドがいくつかあります。

CommentInterface :: getCommentedEntity は、コメントが添付されているエンティティオブジェクトを取得する必要があります。

そう

if ($entity instanceof \Drupal\comment\CommentInterface) {
   $commentedEntity = $entity->getCommentedEntity();
   if ($commentedEntity && $commentedEntity instanceof \Drupal\node\NodeInterface) {
     // The entity that the comment is attached to is a node.
     // Do something with the commented entity.
   }
}
2
mradcliffe