Question

I custom add to cart module on Magento 2 and keep message like Magento core.

if (!$this->_checkoutSession->getNoCartRedirect(true)) {
    if (!$this->cart->getQuote()->getHasError()) {
        $message = __('You added %1 to your shopping cart.', $product->getName());
        $this->messageManager->addSuccessMessage($message);
    }
    return $this->goBack(null, $product);
}

After add to cart success, it return message "Product name add to cart success". But when I access to another page, that message still display.

Ex: I clicked add to cart, when it was loading, I quickly clicked to cart(checkout/cart). Success message was display at there. How can I remove that message, I just want it display one time at product(where click add to cart) page. I use Magento 2.0.7

Was it helpful?

Solution

[Update]

After all, I found a solution for this problem. It's made me sweat too much.

Message was inited at messages.phtml on Magento_Theme package(module-theme\view\frontend\templates\messages.phtml).

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<div data-bind="scope: 'messages'">
    <div data-bind="foreach: { data: messages().messages, as: 'message' },attr:{class:((messages().messages && messages().messages.length > 0)?'messages block __caution mB30':'')}" class="">
    <p class="caution_text" data-bind="html: message.text, visible:message.text!='One or more input exceptions have occurred.'"></p>
</div>

So I think we have to remove message after it display. So I override magento theme and add this script end of messages.phtm file. It works like a charm.

<script>
    require(['jquery', 'jquery/jquery-storageapi'], function($) {
        var storage = $.initNamespaceStorage('mage-cache-storage').localStorage;
        storage.remove('messages');
    });
</script>

Hope this help!

OTHER TIPS

For remove message in Magento 2 try this in phtml or js file:

<script>
require(['jquery', 'jquery/jquery-storageapi'], function($) {
    $.cookieStorage.set('mage-messages', '');
});
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top