How to Add a Custom Admin System Message in Magento 2

Magento uses notification messages to improve user experience. You can simply add any message using the Message Manager to notify users whether the result of an action is successful or not.

In this blog post we will cover one type of the notifications – Admin System Messages. This type of notifications will be shown in a pop-up block and will be present in the admin panel as a reminder for an admin user until a special condition is met. These notifications can vary from messages about invalidated indexes to vulnerability issues. Adding custom system messages can be helpful and we are going to show you how to do it in few simple steps.

To add a custom system message you need to:

  1. Register a new message in the message list;
  2. Create a model class for the new message, which implements few necessary methods for further message handling.

The "\Magento\Framework\Notification\MessageList" class is responsible for processing the list of system messages. If you open this class and look through the code, you will see that it just iterates through the registered system messages to process them. You may also notice that the model class must implement the "\Magento\Framework\Notification\MessageInterface" system message interface to be recognized as a system message.

Here is the code snippet from _loadMessages method of MessageList class:

foreach ($this->_messageClasses as $key => $messageClass) {
   if (!$messageClass) {
       throw new \InvalidArgumentException('Message class for message "' . $key . '" is not set');
   }
   $message = $this->_objectManager->get($messageClass);
   if ($message instanceof \Magento\Framework\Notification\MessageInterface) {
       $this->_messages[$message->getIdentity()] = $message;
   } else {
       throw new \UnexpectedValueException("Message class has to implement the message interface.");
   }
}

The list of configured message classes should be passed as an array parameter ($messages) into MessageList’s constructor method. Using the Magento 2 best practices – each item of this array should be added using the Dependency Injection. So right after the merging process is over, we will get the configuration XML node very similar to the following. So you can see the definition of all available system messages in Magento 2 by default.

<type name="Magento\Framework\Notification\MessageList">
    <arguments>
        <argument name="messages" xsi:type="array">
            <item name="security" xsi:type="string">Magento\AdminNotification\Model\System\Message\Security</item>
            <item name="cacheOutdated" xsi:type="string">Magento\AdminNotification\Model\System\Message\CacheOutdated</item>
            <item name="media_synchronization_error" xsi:type="string">Magento\AdminNotification\Model\System\Message\Media\Synchronization\Error</item>
            <item name="media_synchronization_success" xsi:type="string">Magento\AdminNotification\Model\System\Message\Media\Synchronization\Success</item>
            <item name="recreated_integration_message" xsi:type="string">Magento\Integration\Model\Message\RecreatedIntegration</item>
            <item name="indexer_invalid_message" xsi:type="string">Magento\Indexer\Model\Message\Invalid</item>
            <item name="tax" xsi:type="string">Magento\Tax\Model\System\Message\Notifications</item>
        </argument>
    </arguments>
    ...
</type>

Based on the performed research, now we can simply add our own message implementation. Let’s do it!

We start with adding a new item into the message list, which will point to the corresponding model class. It can be done via the Dependency Injection. Just add the following "type" node into the “<YourVendorName>/<YourModuleName>/etc/adminhtml/di.xml” file of your module as shown below.

<?xml version="1.0"?>
<!--
/**
* @author Atwix Team
* @copyright Copyright (c) 2017 Atwix (https://www.atwix.com/)
* @package Atwix_AdminNotifications
*/

//File: app/code/Atwix/AdminNotifications/etc/adminhtml/di.xml
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <type name="Magento\Framework\Notification\MessageList">
       <arguments>
           <argument name="messages" xsi:type="array">
               <item name="customSystemMessage" xsi:type="string">Atwix\AdminNotifications\Model\System\Message\CustomSystemMessage</item>
           </argument>
       </arguments>
   </type>
</config>

Now we should create a Message Model Class itself. As it was said before – this class must implement the "\Magento\Framework\Notification\MessageInterface" interface.

Here is an example of the simplest message class realization.

<?php
/**
* @author Atwix Team
* @copyright Copyright (c) 2017 Atwix (https://www.atwix.com/)
* @package Atwix_AdminNotifications
*/

//File: app/code/Atwix/AdminNotifications/Model/System/Message/CustomSystemMessage.php

namespace Atwix\AdminNotifications\Model\System\Message;

use Magento\Framework\Notification\MessageInterface;

/**
* Class CustomNotification
*/
class CustomSystemMessage implements MessageInterface
{
   /**
    * Message identity
    */
   const MESSAGE_IDENTITY = 'atwix_system_message';

   /**
    * Retrieve unique system message identity
    *
    * @return string
    */
   public function getIdentity()
   {
       return self::MESSAGE_IDENTITY;
   }

   /**
    * Check whether the system message should be shown
    *
    * @return bool
    */
   public function isDisplayed()
   {
       // The message will be shown
       return false;
   }

   /**
    * Retrieve system message text
    *
    * @return \Magento\Framework\Phrase
    */
   public function getText()
   {
       return __('Atwix System Message Text.');
   }

   /**
    * Retrieve system message severity
    * Possible default system message types:
    * - MessageInterface::SEVERITY_CRITICAL
    * - MessageInterface::SEVERITY_MAJOR
    * - MessageInterface::SEVERITY_MINOR
    * - MessageInterface::SEVERITY_NOTICE
    *
    * @return int
    */
   public function getSeverity()
   {
       return self::SEVERITY_MAJOR;
   }
}

You can see that there are four message types available. And each one is defined as a constant value:

  • Critical (SEVERITY_CRITICAL)
  • Major (SEVERITY_MAJOR)
  • Minor (SEVERITY_MINOR)
  • Notice (SEVERITY_NOTICE)

Clear cache of your Magento installation, login into the Admin Panel and enjoy. We have our own custom Admin System Message working.

Custom admin system notification in Magento 2

Next time we will dive into the Magento 2 notification system, how to create your own notifier, and what is the difference between admin system messages and notifications. Stay tuned!

Don’t skip –

Read more: