6

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

4

[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!

  • Which version of Magento are you using? – bondimedical Jan 24 '17 at 6:18
  • I add tag 2.0.7 above – Henry Bui Jan 24 '17 at 6:21
  • I am using 2.1.3 and it has the same problem – bondimedical Jan 24 '17 at 6:22
  • Was my answer help you fix it? – Henry Bui Jan 24 '17 at 9:08
  • no it doesn't work on my version of Magento – bondimedical Jan 25 '17 at 5:44
0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.