Advertisements

How to create a custom admin notification in Magento 2

Today we will create a function that will add a notification message with the critical icon “Notification World".

It takes only two-step and the rest part of the code is your logic when to display it and when to not.

Step 1: Create a di.xml file

Step 2: Notification Model file

    <?xml version="1.0" encoding="utf-8"?>

    <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="Nd_Theme" xsi:type="string">Nilesh\Prefech\Model\System\Message\Notification\Alert</item>
                </argument>
            </arguments>
        </type>
    </config>

<?php

namespace Nilesh\Prefech\Model\System\Message\Notification;

use Magento\Framework\Notification\MessageInterface;
use Magento\Framework\Phrase;

class Alert implements MessageInterface
{
    private $message;

    /**
     * Messages constructor.
     */
    // public function __construct(
    // ) {
    // }

    /**
     * @return Phrase|string
     */
    public function getText()
    {
        return __($this->message);
    }

    /**
     * @return string
     */
    public function getIdentity()
    {
        return sha1('Nilesh_Account_Notification');
    }

    /**
     * @return bool
     */
    public function isDisplayed()
    {
        $isDisplay = '';

        /* Condition goes here to display notification or not */

        $this->buildMessage($isDisplay);
        return true;
    }

    /**
     * @return int
     */
    public function getSeverity()
    {
        // SEVERITY_CRITICAL
        // SEVERITY_MAJOR
        // SEVERITY_MINOR
        // SEVERITY_NOTICE
        return MessageInterface::SEVERITY_CRITICAL;
    }

    /**
     * Set the value of the message
     *
     * @param array $invalidStores
     */
    private function buildMessage($invalidStores)
    {
        $message = '';

        $message = '<span class="nd_custom_notification">'. __("Notification World"). '</span>';

        /** @phan-suppress-next-line PhanTypeMismatchArgument */
        $this->message = __($message);
    }
}

OutPut: After cache flush ( if not logout and re login )

How to create a custom admin notification in Magento 2 - Admin Panel

You all are the semicolon to my statements; Please support me; Thanks