How To Display Error, Success, & Warning Message In Magento 2
A Magento 2 storefront can be made interactive with the visitors in order to improve the on-site experience, guide them through the store, or restrict them for certain actions.
For example, display success message on successful account creation, an error message on the wrong password for login, or a warning message when the user is about to violate a rule set by the store admin.
In this way, make the Magento 2 store user interface interactive to engage with the visitors. And the below code can be implemented to display error, success, & warning message in Magento 2.
Method to display error, success, & warning message in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace Vendor\Extension\Controller\Index; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\App\Action\Action; class Submit extends Action { protected $messageManager; public function __construct(Context $context, ManagerInterface $messageManager) { $this->messageManager = $messageManager; return parent::__construct($context); } public function execute() { $this->messageManager->addError(__("Error")); $this->messageManager->addWarning(__("Warning")); $this->messageManager->addNotice(__("Notice")); $this->messageManager->addSuccess(__("Success")); } } |
Any doubts about the implementation are welcome in the Comments section below. I’d solve them asap.
Feel free to share the post via social media among the fellow developers.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
Short & Sweet Way to Get Shipping Method From Order in Magento
Easily Learn to Set up Order Confirmation Email in Magento 2
Next