I'm working on a project where I have to notify users when a new node is published or a new comment is created. To achieve this, I've installed the Message subscribe module.
I've configured few flags that seem to work: Users can subscribe to new nodes; when I create a new node, I can flag it.
I've also configured messages, but when I create a new node, no email is sent to users.
I've taken a look at Message Subscribe Module (tje module documentation) and I've found few hooks to make it work. I tried them, but they didn't help: No email is sent.
function mymodule_notification_node_presave(\Drupal\Core\Entity\EntityInterface $node) {
// Get node where comment was posted.
// $node = $comment->get('entity_id')->first()->get('entity')->getTarget()->getValue();
// Call message notify service.
if($node->isPublished()){ //uncomment if need to send only when node published.
$notifier = \Drupal::service('message_notify.sender');
// Create a message with node author as message creator.
$message = Message::create(['template' => 'node_notification', 'uid' => $node->getOwnerId()]);
$message->set('field_text_message', 'text message');
$message->save();
// Send message to message creator(in this case = node author).
$notifier->send($message);
} //isPublished if close
}
/*
* Implements hook_node_insert().
*/
function mymodule_notification_node_insert($node) {
$message = message_create('node_notification', array('uid' => $node->uid));
$wrapper = entity_metadata_wrapper('message', $message);
$wrapper->field_node_ref->set($node);
//$wrapper->save(); <- don't need - message_notify_send_message does this
$notifier = \Drupal::service('message_notify.sender');
$notifier->send($message);
}
/**
* Implements hook_node_update().
*/
function mymodule_notification_node_update(Node $node) {
$message = Message::create([
'template' => 'update_node',
'uid' => $node->getOwnerId(),
]);
$message->set('field_node_reference', $node);
$message->set('field_published', $node->isPublished());
$message->save();
$subscribers = \Drupal::service('message_subscribe.subscribers');
$subscribers->sendMessage($node, $message);
}
Do you have any idea about what I can do wrong?
I have also seen How to use Message Subscribe module? but it didn't help me.
_notification
part. Your hook needs to be structure asmymodule_node_presave(Drupal\node\NodeInterface $node) {
\Drupal::logger('my_module')->notice('It is working!');
and then check the Drupal log/admin/reports/dblog
to see if you see the "It is working!" message, this way you can see/tell if your hooks are indeed firing.