Today we are discussing how to update mini cart after adding product in cart.
In magento 2 when we add a product programmatically then mini cart is not updated automatically, we have to update it by the code.
Firstly, we have to write code for adding product in cart programmatically.
Here is a link in which we discuss about how to add product programmatically.
In the above blog we are using controller named: Index controller with AddProducttocart action.
now for the cart updation we have to create a file at path:
Webkul\Hello\etc\frontend\sections.xml
Add following code in this 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="hello/index/addProducttocart"> <section name="cart"/> </action> </config>
Here, in section.xml we have to define,
action name: here in action name we define modulename_controller_action name, after which we want to update cart.
section name: is which section you want to update, here we want to update cart section.
and these sections are realated to customer that’s why we define Magento_Customer:etc/sections.xsd in the config tag.
After adding this file your cart will automatically get update after hello/index/addProducttocart controller execution.
I hope this blog will help you with How to Update cart after Adding Product Programmatically in Magento 2. You may also check our wide range of best Magento 2 Extensions.
Please reach out to our team via a support ticket if you have any queries.
Try this and if you have any queries then just comment below 🙂
Do you know how to do this with an API, instead of an action in controller?
For example, if I use an API like /V1/badgemakerapi/addToCart to add product to cart (it works properly). How can I update that mini cart?