3

I'm using Drupal 8. I would like to close the comment for the node, once someone commented on that node. But I don't know how to disable the comment for a specific node programmatically.

my_module_comment_insert ($entity) //implement the comment insert hook
{
    $node = $entity->getCommentedEntity();//get the attached comment node.
    // How to implement code here to disable comment for the $node? 
}

1 Answer 1

4

In D8, the comments are stored as field containing various comment properties including comment status.

You can disable node/entity comments using something like below:

use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;

/**
 * Implements hook_comment_insert().
 */
function [MODULE_NAME]_comment_insert($comment) {
  // Get comment field name, default comment.
  $field_name = 'comment'; // $comment->getFieldName();

  // Get entity.
  $node = $comment->getCommentedEntity();
  $node->get($field_name)->status = CommentItemInterface::CLOSED;
  $node->save();
}
1
  • Glad it helped.
    – Yogesh
    Feb 22, 2017 at 4:39

Your Answer

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

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