logo

Programmatically add comment drupal 8

06
December

Programmatically add comment drupal 8
By: Anonymous | Published On: Mon, 12/06/2021 - 16:10

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

Need Help ?