Creating Message Instances

Last updated on
30 April 2025

The Message module does not come with a user interface for creating messages. Partly, this is because the primary purpose of the module is as a logging utility. The other reason is to leave developers the complete flexibility to create messages according to their specific requirements. The following code snippet provides a basic example of how to create a message.

Drupal 7:

The module Foo implements hook_node_insert that is fired whenever a new node is created. In the first line of the hook function the message_create method is called. The arguments passed are the message type foo_message_type and an array of values. In this case, the array includes the uid of node author. Once the message entity has been created (it is not yet saved) an Entity Metadata Wrapper is used to attach an entity reference field so the message retains a reference to the node that was inserted. Finally, the wrapper is used to save the message entity.

/*
 * Implements hook_node_insert().
 */
function foo_node_insert($node) {

  $message = message_create('foo_message_type', array('uid' => $node->uid));

  $wrapper = entity_metadata_wrapper('message', $message);
  $wrapper->field_node_ref->set($node);
  $wrapper->save();
}

Drupal 8:

The same code for Drupal 8 varies slightly to match D8's object-oriented nature. As in the D7 code, the first line creates the message with Message::create(). (Make sure you've added the use Drupal\message\Entity\Message; code to the top of your php file so Drupal will know how to create a "Message" object.) The arguments passed are an array of values, including the message template type foo_message_type. In this case, the array also includes the uid of node author, which will be the message author as well. Once the message entity has been created we use Drupal's core field properties to attach an entity reference field so the message retains a reference to the node that was inserted. Finally, we save the message entity.

use Drupal\message\Entity\Message;

/*
 * Implements hook_node_insert().
 */
function foo_node_insert($node) {
  $message = Message::create(['template' => 'foo_message_type', 'uid' => $node->getOwnerId()]);
  $message->set('field_node_ref', $node);
  $message->save();
}

Help improve this page

Page status: Not set

You can: