How to Show Success and Error Messages in Magento 2

Providing appropriate feedback to the customer about the completeness of their action is the most important thing on the website. Either it may success or failure, provide the appropriate message to the customer about what they have done. In Magento 2, showing success/error message is quite simple and here is the blog which helps you to show the success and error messages by using the core functionality.

Display Messages Using Message Manager:

In Magento 2, the messaging is handled by the message manager interface. So in order to show the messages, we have to inject the object of message manager interface \Magento\Framework\Message\ManagerInterface in the constructor of our class file and access it as follows,

protected $messageManager;

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

public function execute() {
    ...
    try{
        $anyModel->save();
        $this->messageManager->addSuccess(
            __('The data updated successfully')
        );
    }catch (\Exception $e) {
        $this->messageManager->addError(
            __('Sorry, something went wrong and couldn\'t able to update the data.')
        );
    }
    ...
}

By using message manager interface, we can add the following four different type of messages,

$this->messageManager->addSuccess(__('Success'));
$this->messageManager->addError(__('Error'));
$this->messageManager->addWarning(__('Warning'));
$this->messageManager->addNotice(__('Notice'));

If you want to change the message displaying location in frontend, add the following code in your design layout XML file under the body tag to show the message in your desired place,

<referenceContainer name="page.messages">
    <block class="Magento\Framework\View\Element\Template" name="ajax.message.placeholder" template="Magento_Theme::html/messages.phtml"/>
    <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
</referenceContainer>

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *