Magento 2 – How to Create a Custom Admin Notification

adminhtmladminnotificationmagento2

I want to create a custom admin notification message for a module im developing like the one on the image below. I want the notification to remain visible in all admin pages until a certain condition has been met.

enter image description here

There is another thread on this subject but i couldn't find how to get the model class that implements \Magento\Framework\Notification\MessageInterface to be executed. The thread author mentioned that a dependency to Magento_AdminNotification is needed.

Is that achieved on the di.xml file? A more detailed explanation would be very helpful.

Best Answer

I figured out how to do it. I was writing the di.xml file on the wrong directory.

To get your module's custom notification class to run, you need to create the file VendorName/ModuleName/etc/adminhtml/di.xml with the following code:

<?xml version="1.0"?>
<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="yourClassName" xsi:type="string">VendorName\ModuleName\Model\System\Message\YourClassName</item>
            </argument>
        </arguments>
    </type>
</config>

Then you have to create the VendorName\ModuleName\Model\System\Message\YourClassName.php class file with the following code:

<?php

namespace VendorName\ModuleName\Model\System\Message;

class YourClassName implements \Magento\Framework\Notification\MessageInterface
{

    public function getIdentity()
    {
        // Retrieve unique message identity
        return 'identity';
    }

    public function isDisplayed()
    {
        // Return true to show your message, false to hide it
        return true;
    }

    public function getText()
    {
        // Retrieve message text
        return 'Notification message text goes here';
    }

    public function getSeverity()
    {
        // Possible values: SEVERITY_CRITICAL, SEVERITY_MAJOR, SEVERITY_MINOR, SEVERITY_NOTICE
        return self::SEVERITY_MAJOR;
    }
}
Related Topic