3

I have have a content type (Stuff) with an entity reference field (comments) for comments (their type is Stuff comments) with a single field (comment_body).

Inside a controller, I loaded a node by its ID.

How do I get the list of all the comments for that node?

0

3 Answers 3

3

To answer my own question I guess(better alternatives are more than welcome).

use Drupal\Core\Entity\EntityTypeManagerInterface;

class SomeRepository {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entity_type_manager;

  /**
   * ProductRepository constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entity_type_manager = $entity_type_manager;
  }

  /**
   * @param $node_id
   *
   * @return array|null
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function getNodeComments($node_id) {
    try{
      $node = $this->entity_type_manager
        ->getStorage('node')
        ->load($node_id);
    }catch(\Exception $exception) {
      // log here
      // rethrow error or return, whatever works for you
      return NULL;
    }

    try{
      $comment_ids = $this->entity_type_manager
        ->getStorage('comment')
        ->getQuery('AND')
        ->condition('entity_id', $node->id())
        ->condition('entity_type', 'node')
        ->sort('cid', 'DESC')
        ->execute();
    }catch(\Exception $exception) {
      // log here
      // rethrow error or return, whatever works for you
      return NULL;
    }

    if(empty($comment_ids)) {
      return [];
    }

    $comments = $this->entity_type_manager
      ->getStorage('comment')
      ->loadMultiple($comment_ids);

    $comments_array = [];

    foreach($comments as $comment) {
      // Loop over and get whichever fields you want from the comments
      $comments_array[$comment->id()] = [
        'cid' => $comment->id(),
        'owner_id' => $comment->getOwnerId(), // node to which this comment belongs
        'some_field' => $comment->get('some_field')->value
      ];
    }

    return $comments_array;
  }
}
2
  • I posted my answer while you were posting yours :D Commented Sep 6, 2018 at 12:26
  • A minor thing - $comment->getOwnerId(); gives you the user ID (uid) of the comment author, not the node ID. (v. helpful answer btw, was looking everywhere.) Commented Sep 8, 2018 at 19:38
3

Assuming the your node is a variable $node:

$entity_manager = \Drupal::entityTypeManager();
  try {
    /** @var \Drupal\comment\CommentStorageInterface $storage */
    $storage = $entity_manager->getStorage('comment');
    /** @var \Drupal\comment\CommentFieldItemList $commentField */
    $commentField = $node->get('comment');
    $comments = $storage->loadThread($node, $commentField->getFieldDefinition()->getName(), \Drupal\comment\CommentManagerInterface::COMMENT_MODE_FLAT);
    if (empty($comments)){
      return;
    }
    /** @var \Drupal\comment\Entity\Comment $comment */
    foreach ($comments as $comment) {
      //Logic here
    }

  } catch (\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException $e) {
  } catch (\Drupal\Component\Plugin\Exception\PluginNotFoundException $e) {
  }

This will get you all the comments of that node. You can play with the \Drupal\comment\CommentManagerInterface to get a threaded version of the comments.

2
  • This code will get all the comments independently from their type, while the OP is speaking of a single comment type.
    – avpaderno
    Commented Sep 6, 2018 at 20:04
  • I think it'll grab the comments referenced by the field in the node. Anyway, it was worth the try Commented Sep 6, 2018 at 20:53
-1

You can do something like

foreach ($stuff->get('comments')->referencedEntities() as $comment) {
   ..do whatever on entity comment ..
}
3
  • In the foreach you can collect the id's to an array and call "Comment::loadMultiple()" later. Commented Sep 6, 2018 at 11:28
  • 1
    Unfortunately I'm getting a fatal Error: Call to undefined method Drupal\comment\CommentFieldItemList::referencedEntities()
    – Andrew
    Commented Sep 6, 2018 at 11:36
  • This doesn't work in Drupal 8.7.x, as @Andrew has said, it throws a Fatal Error.
    – tobynew
    Commented Aug 15, 2019 at 12:45

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.