With the growing use of the internet and technology, several changes & enhancement happen into design, layout, and code to provide a better & a richer experience to the users. Also, Magento moved smartly with concepts like knockout js, AJAX other add ons that allows web applications to send and retrieve data from a server asynchronously without refreshing or reloading. This technique helps reducing server request and saves time by reloading only one portion or section of the webpage.
For example, we have one extension in Magento 2 that offers Ajax login functionality and we want to restore old cart items once a user successfully login to their account. To do the same we only need to refresh a mini cart only, not the whole page.
By default, Magento 2 creates a small group of data and each group has a unique name/key. So, if we want to refresh a particular section we can use its group key to refresh data. In all new Magento 2, it stores data at both hands, so we also need to update local storage data of browser if we want to refresh a particular portion.
To do the same, first you need to create “di.xml” at this path.
app\code\Vendor\Extension\etc\di.xml
1 2 3 4 5 6 7 8 9 10 |
<pre class="lang:default decode:true"> <type name="Magento\Customer\CustomerData\SectionPoolInterface"> <arguments> <argument name="sectionSourceMap" xsi:type="array"> <item name="cart" xsi:type="string">Magento\Checkout\CustomerData\Cart</item> <item name="directory-data" xsi:type="string">Magento\Checkout\CustomerData\DirectoryData</item> </argument> </arguments> </type> </pre> |
Now, in above code we just register cart and directory-data in customer Data section. For that we need to create section.xml using below code at this path.
app\code\Vendor\Extension\etc\frontend\section.xml
1 2 3 4 5 6 7 8 9 |
<pre class="lang:default decode:true"> <?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="routername/controller/action"> <section name="cart"/> </action> </config> </pre> |
So, now whenever we call action like “ajaxlogin/index/getlogin” Magento will consider the current cart section is outdated and it re-initialize the cart section.
You can also refresh the cart section on each request, by using * instead of action.
That’s it for today, Let us know if you are facing an issue while implementing using this code by commenting below.
Happy Coding!