Magento 2 Sections

In Magento 2, we have a piece of customer data grouped together which we call it as a section. Every Magento 2 section is represented by the key which is used to access and manage the data itself where every key will be a section. Lets create a section via following code snippet.

There are following steps to create sections:

Step 1: Create an xml file in etc/frontend/di.xml file as shown below.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\CustomerData\SectionPoolInterface">
        <arguments>
            <argument name="sectionSourceMap" xsi:type="array">
                <item name="customsection" xsi:type="string">Magemeta\Section\CustomerData\CustomSection</item>
            </argument>
        </arguments>
    </type>
</config>

We have given item name=”customsection” which defines its data source as Magemeta\Section\CustomerData\CustomSection class.

Step 2: Next we need to create getSectionData() method in Magemeta\Section\CustomerData\CustomSection.php file where this method(function) is responsible to set and return the data in different sections.

<?php
namespace Magemeta\Section\CustomerData;
use Magento\Customer\CustomerData\SectionSourceInterface;
 
class CustomSection implements SectionSourceInterface
{
    /**
     * {@inheritdoc}
     */
    public function getSectionData()
    {
        return [
            'msg' =>'Custom data from section area',
        ];
    }
}

To verify our custom section data, we need to check the local storage of our browser.

Step 3: Next we need to call our phtml template file customsection.phtml on product view page which will fetch the message that we have set in our custom section. We have to call this phtml file by adding to layout xml of any layout handle like cms_index_index.

<?xml version="1.0"?>
 
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template"  name="custom_section" template="Magemeta_Section::customsection.phtml">
            </block>
        </referenceContainer>
    </body>
</page>

phtml Template file to add: customsection.phtml

<div class="mg-customsection"data-bind="scope: 'section'">
    <p data-bind="text: customsection().msg"></p>
</div>
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "section": {
                        "component": "Magemeta_Section/js/section"
                    }
                }
            }
        }
    }
</script>

Step 4: In template file, we need to bind the div.mg-customsection with the component section. Now, we will create the Magemeta/Section/frontend/web/js/section.js file.

define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
], function (Component, customerData) {
    'use strict';
    
    return Component.extend({
        /** @inheritdoc */
        initialize: function () {
            this._super();
            this.customsection = customerData.get('customsection'); //pass our custom section name
        }
    });
});

Now just need to refresh our cache and when we will visit our layout page, there we can see the message set in section.

In section.js file, we have used Magento_Customer/js/customer-data as this js file which is responsible for setting and getting section data. Section data gets updated when ajax call with post, put, delete requests are made.

Advantages of Using Section

When caching is enabled the whole page content is cached which helps us to dynamically manage the components of page. Lets see the example, if the complete page is cached and when the customer logs in, only the components get updated with the value from the section as we can see customer name, cart, wish list are all managed by section.

All section data is fetched in 1 single ajax call, so the number of ajax requests are reduced to a huge number which is doing load optimization in Magento.

We can also manage when to update the section data by using etc/frontend/sections.xml.

Hope this helps you guys!

Leave a Reply