Display notification messages in Magento 2

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


If you are using a controller, then most probably you have extended

  1. \Magento\Framework\App\Action\Action

This injects the \Magento\Framework\Message\ManagerInterface object in its __construct function using the

  1. \Magento\Framework\App\Action\Context $context object

So to display a message,

Success -

  1. $this->messageManager->addSuccess( __('This is your success message.') );

Error -

  1. $this->messageManager->addError( __('This is your error message.') );

Warning -

  1. $this->messageManager->addWarning( __('This is your warning message.') );

Notice -

  1. $this->messageManager->addNotice( __('This is your notice message.') );

In other case

  1. class TonyBlog
  2. {
  3. /**
  4. * @var \Magento\Framework\Message\ManagerInterface
  5. */
  6. private $messageManager;
  7. public function __construct(
  8. \Magento\Framework\Message\ManagerInterface $messageManager
  9. )
  10. {
  11. $this->messageManager = $messageManager;
  12. }
  13. public function tonyFunction()
  14. {
  15. $this->messageManager->addSuccess('Add your success message');
  16. }
  17. }

That’s all.