Jigar KarangiyaJigar Karangiya

How to clear previous messages in MessageManager programmatically?

JK
Jigar Karangiya
· 1 min read
How to clear previous messages in MessageManager programmatically?

Hello Devs,

In today’s tutorial, we will see how we can programmatically clear previous messages in MessageManager to remove unwanted duplicate messages.

During development, you have faced the issue that some messages are not getting cleared when performing the same action again and it causes multiple messages on screen.

We can easily clear the message stack using the below default function.

Put the below code in your custom controller.

php
<?php
namespace Jigar\ClearMessageTutorial\Controller\Index;
 
class Index extends \Magento\Framework\App\Action\Action
{
 
	protected $_pageFactory;
 
	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $pageFactory)
	{
		$this->_pageFactory = $pageFactory;
		return parent::__construct($context);
	}
 
	public function execute()
	{
		/*Your controller code*/
		$this->messageManager->getMessages(true);
		$message = __('Above line will remove all old messages from messageManager.');
		$this->messageManager->addErrorMessage($message);
		/*Your controller code*/
	}
 
}

As you can see in the above example, We have added $this- >messageManager->getMessages(true); before our message. So it will clear all previous messages from the session and load messages after that line.

You can check the function defined in vendor/magento/framework/Message/Manager.php

php
/**
     * @inheritdoc
     *
     * @param bool $clear
     * @param string|null $group
     * @return Collection
     */
    public function getMessages($clear = false, $group = null)
    {
        $group = $this->prepareGroup($group);
        if (!$this->session->getData($group)) {
            $this->session->setData($group, $this->messagesFactory->create());
        }
        if ($clear) {
            $messages = clone $this->session->getData($group);
            $this->session->getData($group)->clear();
            $this->eventManager->dispatch('session_abstract_clear_messages');
            return $messages;
        }
        return $this->session->getData($group);
    }

I hope this tutorial was helpful.

See you in the next tutorial.

You might also like :

Add Yes/No Attribute in Magento 2 programmatically

Adobe Commerce Cloud Project Structure

DDEV Docker: How to change the project PHP version?

Securely render Javascript inside Magento 2 template files using PHP

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts