Notification Messages in Magento 2 | Notification System

Display notification messages via notification system in Magento 2

How to display confirmation messages, error or warning to the user is something every theme and/or Magento 2 extension developer should know about. There are four types of notification messages you can use: Error (in red), Notice (yellow), Success (green) and Warning (in grey).

Getting your module to display notifications in Magento 2 is different than in Magento 1, since there are no more session class specific notification messages.

If you need your module to display messages via Magento notification system, we will show you the example of the code you should use.

Note that we are using

\Magento\Framework\Message\ManagerInterface;

in controller construct function.
[codesyntax lang=”php”]

...
protected $_messageManager;

public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Message\ManagerInterface $messageManager) {
        parent::__construct($context);
        $this->_messageManager = $messageManager;
    }
/*
*  Test method for displaying messages
*/
public function addAllMessagesTest() {
        $this->_messageManager->addError(__("Error"));
        $this->_messageManager->addWarning(__("Warning"));
        $this->_messageManager->addNotice(__("Notice"));
        $this->_messageManager->addSuccess(__("Success"));
}
...
}

[/codesyntax]

In this example we are showing all four types of notification messages available in Magento 2 admin.

If you encounter an error you should clear cached files from var\generation and var\cache folder.

Leave a Reply

Your email address will not be published.