06
December
Add this line in head
use Drupal\comment\Entity\Comment;
These are following code format which can use to add comment through custom code in Drupal 8 or 9
$values = [ 'entity_type' => 'node', // required. 'entity_id' => $nid, // required. 'field_name' => 'comment', // required. 'uid' => $uid, // required. 'comment_type' => 'comment', // required. 'subject' => $username, // required. 'comment_body' => $msg, // optional. 'status' => 1, // optional. Defaults to 0. ]; $comment = Comment::create($values); // $comment->set('field_comment_category', 'writer'); // Last, we actually need to save the comment to the database. $comment->save();
If you have added any other fields in comment then you can use as below code format
$comment->set('field_comment_category', 'writer');
In given example I have added a field comment_category
© 2023.ZedAngle. All Rights Reserved.