How to Trigger a Minicart Update After Adding to Cart in Magento 2

magento2

I have the following class i am using to test adding to cart in a custom way;

use Magento\Framework\App\Action;
use Magento\Checkout\Model\Cart;

class Add extends Action\Action
{
    protected $cart;

    public function __construct(
        Action\Context $context,
        Cart $cart
    ){
        $this->cart = $cart;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->cart->addProductsByIds([1])
            ->save();
    }
}

This works great. When you view the cart it shows my item, all looks cool in the database etc. However, the minicart still shows as if there are no items in the basket.

If i then add another product to the cart using the "add to cart" button on the product or listing pages it adds to the cart and updates the minicart to show both items.

Where does it trigger the minicart to update itself or how does the minicart know it needs to refresh?

Best Answer

Thanks for your help :)

I have found how to trigger it, you need to set up a sections.xml inside etc/frontend of your module that tells Magento which sections to update for a given Ajax call. Here is an example;

<?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="[frontName]/[ActionPath]/[ActionName]">
        <section name="cart"/>
    </action>
</config>

After my Ajax call has finished to [frontName]/[ActionPath]/[ActionName] Magento makes another call to /customer/section/load passing the sections to load.

By default it requests any messages but if you have set up your sections.xml correctly you will also see the section names you have defined in there as well.

Related Topic