How To

Magento 2: Add Swatch Data in Layered Navigation Aggregations in GraphQL

Hello Magento Folks 👋,

Welcome to Magento 2 How-To blog series by MageComp. Today’s article describes Magento 2: Add Swatch Data in Layered Navigation Aggregations in GraphQL. Not to miss out on our previous blog, Magento 2: How to Get System Configurations Value in Email Templates.

Swatch data comes to help in increasing the shopping experience of your store and let the user purchase with ease from your store. Providing the option of swatching data, the user can select color, size, and other options for a particular product just by selection instead of reloading the page. Magento 2 offers adding swatch data in layered navigation aggregations in GraphQL. The query searches for the products that match the specified search criteria.

Let’s get started 🚀

Magento 2: Add Swatch Data in Layered Navigation Aggregations in GraphQL

Step 1: Create file app/code/VENDOR/EXTENSION/registration.php and add the following code:

use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
    ComponentRegistrar::MODULE, 
    'VENDOR_EXTENSION', 
    __DIR__);

 Step 2: Create file app/code/VENDOR/EXTENSION/etc/module.xml and add the following code: 

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VENDOR_EXTENSION" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Store"/>
            <module name="Magento_Catalog"/>
            <module name="Magento_CatalogInventory"/>
        </sequence>
    </module>
</config>

 Step 3: Create file app/code/VENDOR/EXTENSION/etc/schema.graphqls and add the following code:

interface AggregationOptionInterface
{
    swatch_data: SwatchData @doc(description: "Data required to render swatch filter item")
}
type SwatchData
{
    type: String @doc(description: "Type of swatch filter item: 1 - text, 2 - image")
    value: String @doc(description: "Value for swatch item (text or image link)")
}

 Step 4: Create file app/code/VENDOR/EXTENSION/etc/graphql/di.xml and add the following code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\CatalogGraphQl\DataProvider\Product\LayeredNavigation\LayerBuilder" type="VENDOR\EXTENSION\DataProvider\Product\LayeredNavigation\DataProviderAggregationPlugin"/>
</config>

Step 5: Create file app/code/VENDOR/EXTENSION/DataProvider/Product/LayeredNavigation/DataProviderAggregationPlugin.php and add the following code:

<?php

namespace VENDOR\EXTENSION\DataProvider\Product\LayeredNavigation;

use Magento\Eav\Model\Config;
use Magento\Framework\Api\Search\AggregationInterface;
use Magento\Swatches\Block\LayeredNavigation\RenderLayered;
use Magento\Swatches\Helper\Data;
use Psr\Log\LoggerInterface;
use Magento\CatalogGraphQl\DataProvider\Product\LayeredNavigation\LayerBuilder;
use Magento\CatalogGraphQl\DataProvider\Product\LayeredNavigation\LayerBuilderInterface;
use Magento\Framework\Exception\LocalizedException;

class DataProviderAggregationPlugin extends LayerBuilder implements LayerBuilderInterface
{
    private $builders;
    protected $_logger;
    protected $eavConfig;
    private $swatchHelper;
    private $renderLayered;

    public function __construct(
        array $builders,
        LoggerInterface $logger,
        Config $eavConfig,
        Data $swatchHelper,
        RenderLayered $renderLayered
    )
    {
        $this->builders = $builders;
        $this->_logger = $logger;
        $this->eavConfig = $eavConfig;
        $this->swatchHelper = $swatchHelper;
        $this->renderLayered = $renderLayered;
    }

    public function build(
        AggregationInterface $aggregation,
        ?int $storeId
    ): array
    {
        $layers = [];
        foreach ($this->builders as $builder)
        {
            $layers[] = $builder->build($aggregation, $storeId);
        }
        $layers = \array_merge(...$layers);
        foreach ($layers as $key => $value) 
        {
            $attribute = $this->eavConfig->getAttribute('catalog_product', $layers[$key]['attribute_code']);
            if ($this->swatchHelper->isSwatchAttribute($attribute))
            {
                for ($i = 0; $i < count($layers[$key]['options']); $i++)
                {
                    $hashcodeData = $this->swatchHelper->getSwatchesByOptionsId([$layers[$key]['options'][$i]['value']]);
                    $typeName = $this->getswatchType($hashcodeData[$layers[$key]['options'][$i]['value']]['type']);

                    $temp = [
                        'type' => $typeName,
                        'value' => $hashcodeData[$layers[$key]['options'][$i]['value']]['value']
                    ];

                    $layers[$key]['options'][$i]['swatch_data'] = $temp;
                }
            }
        }

        return \array_filter($layers);
    }

    public function getswatchType($valueType)
    {
        switch ($valueType)
        {
            case 0:
                return 'TextSwatchData';
            case 1:
                return 'ColorSwatchData';
            case 2:
                return 'ImageSwatchData';
            break;
        }
    }
}

GraphQL Request:

{
    products(filter: {category_id: {eq: "2"}})
    {
        aggregations
        {
            attribute_code
            count
            label
            options
            {
                label
                value
                count
                swatch_data
                {
                    value
                    type
                }
            }
        }
    }
}

GraphQL Response:

{
    "data":
    {
        "products":
        {
            "aggregations":
            [
                {
                    "attribute_code": "color",
                    "count": 7,
                    "label": "Color",
                    "options":
                    [
                        {
                            "label": "Red",
                            "value": "5437",
                            "count": 5,
                            "swatch_data":
                            {
                                "value": "#eb0c0c",
                                "type": "ColorSwatchData"
                            }
                        },
                        {
                            "label": "Blue",
                            "value": "5438",
                            "count": 3,
                            "swatch_data":
                            {
                                "value": "#0d4aff",
                                "type": "ColorSwatchData"
                            }
                        }
                    ]
                },
                {
                    "attribute_code": "texture",
                    "count": 6,
                    "label": "Texture",
                    "options":
                    [
                        {
                            "label": "model2",
                            "value": "5432",
                            "count": 5,
                            "swatch_data":
                            {
                                "value": "/t/1/t1.jpeg",
                                "type": "ImageSwatchData"
                            }
                        },
                        {
                            "label": "model3",
                            "value": "5433",
                            "count": 2,
                            "swatch_data":
                            {
                                "value": "/t/3/t30.jpeg",
                                "type": "ImageSwatchData"
                            }
                        } 
                    ]
                }
            ]
        }
    }
}

Conclusion:

With the help of the above code, you will be able to add swatch data in layered navigation aggregations in GraphQL. If you stuck anywhere while executing the above code, let me know in the comment section. Help your Magento friends to implement the same by sharing the article with them. Stay connected!

Happy Swatching 😊

Click to rate this post!
[Total: 5 Average: 4.2]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 day ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago