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:
<?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")); } }
That’s it.
To display a custom message when processing an order that contains a gift in the admin panel, you can add the message to the Sales Order View, Invoice View, and Credit Memo View in Magento 2.
Feel free to share the post via social media among the fellow developers.
Thanks.