logo

Drupal8 node commands

alam
13 Jul 2021

Custom code on comment publish in Drupal 8

If you want to add your custom code on published of comment then we can use hook"hook_comment_update"

"$comment->isPublished()" will check comment in published

For example you want to send mail when comment published or unpublished so you can follow these step

Open your .module file and add the following code, for example your module name is "mymodule" then

 

function mymodule_comment_update($comment) {
	// This code will run on publishing of comment
	if ($comment->isPublished() && !$comment->original->isPublished()) {
		$comment->get('cid')->value				// Return comment ID
		$comment->original->id()				// Return comment ID
		$comment->getOwnerId()					// Return user id of comment owner (who have posted that comment)
		$comment->get('status')->value			// Return Current status of comment, its published or unpublished (1/0)
		$comment->get('subject')->value			// Return subject of comment
		$comment->get('created')->value			// Return comment created date and time in timestamp format
		$comment->get('comment_body')->value	// Return comment body text
		$comment->get('entity_id')->target_id	// Return that Node ID of the content for which comment has been posted
	}
	
	// This code will run on unpublishing of comment reutrn value will be same as comment publishing
	if (!$comment->isPublished() && $comment->original->isPublished()) {
		
	}
}