Reading list Switch to dark mode

    Update Mini Cart Magento2

    Updated 25 January 2023

    In this blog we will see how to update mini cart in magento2.
    In Magento2 many times it happens, You changed something in cart but it does not reflects in mini cart.
    It happens when you try to change and update cart items programmatically.

    There can be two types of situation.

    • When you are updating cart by submitting form.
    • When you are updating cart without submitting form.

    Update mini cart when you are submitting a form

    Magento provides a way to update minicart if you are submitting a form.
    First of all create sections.xml file in ‘etc/frontend’ folder in your module.
    Now write following code snippet in sections.xml file

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
        <action name="modulename/controler/addProduct">
            <section name="cart"/>
        </action>
    </config>

    action name : action name is controller where you are submitting form.
    So Use this approach whenever you are dealing with a form.
    Example of this situation may be when you want to set custom price of product in your own controller.
    This approach will work when you are using POST or PUT form submitting. It will also work for AJAX request.

    Update mini cart when you are not submitting a form

    In some situations you want to update cart and you don’t want to submit any form.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    In these type of situations you can not use sections.xml file because you are not submitting a form.

    So for these type of situations you can use following code in template file.

    <script>
        require([
            'Magento_Customer/js/customer-data'
        ], function (customerData) {
            var sections = ['cart'];
            customerData.invalidate(sections);
            customerData.reload(sections, true);
        });
    </script>

    So use this code snippet in phtml file and minicart will be updated.
    Example of this situation may be when you want to add and update items in cart on cart view and checkout page.
    So using these two approaches you can update mini cart in any type of situation.

    If you have any issue or query, comment below.

    . . .

    Leave a Comment

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


    3 comments

  • Rajendra pawar
    • Hari Narayan Bairwa (Moderator)
  • Dominic Dambrogia
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home