Magento 2 display success and error messages
Magento 2 offers you a possibility to display success and error messages. This is a great way to give appropriate feedback to a user. This messages can be displayed in adminhtml or in frontend. Use it, but don’t use it too much!
Magento 2 display success and error messages
Messages are a great way to keep in contact to a user, even if you are working on a Magento 2 module without any frontend or adminhtml views. A defined message will appear in a messages block the next time this block refreshes (after a page load or an ajax call). So even for a interface model you can display messages to a user. How does it work?
Working with message manager
Messaging in Magento 2 is handled by a message manager object. So if you want to write messages, you need to get an instance of it. The prefered method is to inject this class into your class by adding this to your __construct method:
1 2 3 4 5 6 7 8 9 10 | protected messageManager; public function __construct( ... \Magento\Framework\Message\ManagerInterface $messageManager, ... ){ $this->messageManager = $messageManager; ... } |
With this, you can call one of the following messages:
1 2 3 4 | $this->messageManager->addError(__("Error")); $this->messageManager->addWarning(__("Warning")); $this->messageManager->addNotice(__("Notice")); $this->messageManager->addSuccess(__("Success")); |
Observer method
If you are on a observer, normally there is no way to display messages. Your observer method may be called during an ajax call which does not reload message block. What to do? A very common way to show error messages is to actually throw an error. For example if you call a:
1 | throw new \Magento\Framework\Exception\CouldNotDeleteException(__("Prices have been changed!")); |
This message is displayed on frontend, because this is the result of your ajax request. I tested this with an sales_order_save_before observer.
Conclusion
Displaying messages to users or administrators is very easy in Magento 2. The only quest is to display only few, but meaningful information at the right time. For this, you should think before you start to code.
The following extension makes this process a lot easier. It lets you display custom messages with 6 different layouts. Display call to action button and a custom URL.
https://www.fmeextensions.com/magento-2-custom-message-display-on-cart-checkout-success-page.html