19

In Magento2, how do we print the input data into notification messages for - Error - Success - Warning - Notice

31

In your class, inject the Message ManagerInterface class:

__construct(\Magento\Framework\Message\ManagerInterface $messageManager) {
    $this->messageManager = $messageManager;
}

Note, Magento has deprecated methods:

$this->messageManager->addSuccess()
$this->messageManager->addError()
$this->messageManager->addWarning() 
$this->messageManager->addNotice()

So instead you should use:

$this->messageManager->addSuccessMessage()
$this->messageManager->addErrorMessage()
$this->messageManager->addWarningMessage() 
$this->messageManager->addNoticeMessage()
  • Would this also work during the onepage checkout, where "everything" is javascript? – peedee May 9 '17 at 9:06
  • Apparently the "page.messages" section gets removed from the checkout through the checkout_index_index.xml file, so messages will not be shown there. I wonder why Magento built it that way. – peedee May 11 '17 at 3:34
17

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

\Magento\Framework\App\Action\Action

https://github.com/magento/magento2/blob/develop/lib/internal/Magento/Framework/App/Action/Action.php

This injects the \Magento\Framework\Message\ManagerInterface object in its __construct function using the \Magento\Framework\App\Action\Context $context object

So to display a message,

  1. Success -

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

  2. Error -

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

  3. Warning -

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

  4. Notice

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

Inside other classes

class Dummy
{

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
   private $messageManager;

   public function __construct(\Magento\Framework\Message\ManagerInterface $messageManager)
   {
       $this->messageManager = $messageManager;
   }

  public function someFunction()
  {
    $this->messageManager->addSuccess('Add your success message');
  }

}

So as far as i have noticed, Magento2 has removed session class specific notification messages.

  • 1
    Magento has deprecated these add<type>() methods. See my answer. – Robert Stanley Oct 20 '16 at 15:38
  • 1
    I have a problem with message, when I add to cart it show success message but when I access to another page it still show that message. How can I remove it when it show at least once time? – Henry Bui Jan 11 '17 at 2:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.