How to clear previous messages in MessageManager programmatically?

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.

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

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

Leave a Reply

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