Site icon MageComp Blog

How to Set Product-wise swatches in Magento 2

How to Set Product wise swatches in Magento 2

We love shopping when choosing product options becomes much easier like color and size option. Swatches provide an alternate way to display the selection of options just by clicking for configurable products rather than choosing an option from typical drop-down options. Also, a few days back we have written a blog on “How to use Configurable Swatches in our Custom Magento Theme” where w, these swatches are only available for the default package. But we provide code through which you can add this feature in your custom theme.
But there is one problem when you create swatches from the product Magento creates global swatches for all the products that create a bad impression on your customers as shown below.

So, we are back with a small piece of code that allows you to set product-wise swatches in your Magento 2 store.
First create “Di.xml” file inside etc folder using below code.
app\code\Vendor\Extension\etc

<pre class="lang:default decode:true">
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Swatches\Block\Product\Renderer\Configurable" type="Vendor\Extension\Block\Product\Configswatch" />
</config>
</pre>

Now Create New Block file name Configswatch.php At this path and add below code to that file.
app\code\Vendor\Extension\Block\Product

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Block\Product;

class Configswatch extends \Magento\Swatches\Block\Product\Renderer\Configurable
{
    protected $_storeManager;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        array $data = []
    )
    {
        $this->_storeManager = $storeManager;
        parent::__construct($context, $data);
    }
    public function getJsonSwatchConfig()
    {
        $attributesData = $this->getSwatchAttributesData();
        $allOptionIds = $this->getConfigurableOptionsIds($attributesData);
        $swatchesData = $this->swatchHelper->getSwatchesByOptionsId($allOptionIds);

        $config = [];
        foreach ($attributesData as $attributeId => $attributeDataArray) {
            if (isset($attributeDataArray['options'])) {
                $config[$attributeId] = $this->addSwatchDataForAttribute(
                    $attributeDataArray['options'],
                    $swatchesData,
                    $attributeDataArray,
                    $attributeId
                );
            }
        }

        return $this->jsonEncoder->encode($config);
    }
    protected function addSwatchDataForAttribute(
        array $options,
        array $swatchesCollectionArray,
        array $attributeDataArray,
        $attributeId=null
    ) {

        $currentStore = $this->_storeManager->getStore();
        $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'/customswatch/';

        $result = [];
        foreach ($options as $optionId => $label) {
            if (isset($swatchesCollectionArray[$optionId])) {
                $result[$optionId] = $this->extractNecessarySwatchData($swatchesCollectionArray[$optionId]);
                $result[$optionId] = $this->addAdditionalMediaData($result[$optionId], $optionId, $attributeDataArray);
                $result[$optionId]['label'] = $label;
                if ($attributeId) {
                    if($this->getProduct()->getId()==2 && $attributeId == 10) {
                        if($optionId == 5) {
                            $result[$optionId]['type'] = 2; // Option Type is Image
                            $result[$optionId]['value'] = $mediaUrl.'blue-jeans.jpg';
                            $result[$optionId]['thumb'] = $mediaUrl.'blue-jeans.jpg';
                        } elseif ($optionId == 6) {
                            $result[$optionId]['type'] = 2; // Option Type is Image
                            $result[$optionId]['value'] = $mediaUrl.'green-jeans.jpg';
                            $result[$optionId]['thumb'] = $mediaUrl.'green-jeans.jpg';
                        }
                    }
                }
            }
        }

        return $result;
    }
}
</pre>

That’s it for today, Let us know if you are facing an issue while implementing swatches using this code by commenting below.

Happy Swatches!

Exit mobile version