How to change product description dynamically in configurable product when click swatches Magento2

Do you want to change the product description on the swatches click of configurable productΒ in Magento2?

The current functionality is in configurable product, if the customer clicks on the swatches then it updates the product image and product price.

Now let’s say you have requirement of updating the product name, description or sku, etc on swatches, how to implement this functionality.

To update product name & sku on swatches, follow this.

In this article, we are going to update product description, see this process step by step. The following steps are:

    • Step 1: Create the module
    • Step 2: Add Product Name information
    • Step 3: Update the product Name on swatches click

We are going to create the module to implement this functionality. Let’s start with the first step:

Step 1: Create the module

Create theΒ registration.phpΒ Β file inΒ app/code/Thecoachsmb/Productmodule/ for theΒ module

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Thecoachsmb_Productmodule',
__DIR__
);

Create directoryΒ app/code/Thecoachsmb/Productmodule/etc

Put this file in it :Β module.xml

<?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="Thecoachsmb_Productmodule" setup_version="1.0.0">
        <sequence>
            <module name="Magento_ConfigurableProduct"/>
            <module name="Magento_Swatches"/>
        </sequence>
    </module>
</config>

Step 2: Add Product Description information

To pass the product name information on swatches click, we need to modify the functionΒ getJsonConfigΒ present in

\Magento\ConfigurableProduct\Block\Product\View\Type\Configurable.php

Now to modify this function, we are going to use plugins.

Now create directoryΒ app/code/Thecoachsmb/Productmodule/etc/frontend/

Put this file in it :Β di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable">
<plugin name="Thecoachsmb_Productmodule_product_block" type="Thecoachsmb\Productmodule\Plugin\Product\View\Type\ConfigurablePlugin" sortOrder="1" />
</type>
<type name="Magento\ConfigurableProduct\Model\Product\Type\Configurable">
<plugin name="Thecoachsmb_Productmodule_product_model" type="Thecoachsmb\Productmodule\Plugin\Product\Type\ConfigurablePlugin" sortOrder="1" />
</type>
</config>

Create directoriesΒ app/code/Thecoachsmb/Productmodule/Plugin/Product/View/Type/

Put this file :Β ConfigurablePlugin.php

<?php 
namespace Thecoachsmb\Productmodule\Plugin\Product\View\Type; 
class ConfigurablePlugin { 
     protected $jsonEncoder; 
     protected $jsonDecoder; 

     public function __construct( 
        \Magento\Framework\Json\DecoderInterface $jsonDecoder, 
        \Magento\Framework\Json\EncoderInterface $jsonEncoder 
    ){ 
        $this->jsonEncoder = $jsonEncoder;
        $this->jsonDecoder = $jsonDecoder;
    }

    public function afterGetJsonConfig(\Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject, $result)
    {
        $result = $this->jsonDecoder->decode($result);
        $currentProduct = $subject->getProduct();

        if ($currentProduct->getName()) {
            $result['productName'] = $currentProduct->getName();
        }

        if ($currentProduct->getSku()) {
            $result['productSku'] = $currentProduct->getSku();
       }

       if ($currentProduct->getDescription()) {
            $result['productDescription'] = $currentProduct->getDescription();
       }
        foreach ($subject->getAllowProducts() as $product) {
            $result['names'][$product->getId()] = $product->getName();
            $result['skus'][$product->getId()] = $product->getSku();
            $result['desc'][$product->getId()] = $product->getDescription();
        }
        return $this->jsonEncoder->encode($result);
    }
}

Now, we have passed product name to the js file which updates the data.

Also we need to select description from product collection, so for this

app\code\Thecoachsmb\Productmodule\Plugin\Product\Type\ConfigurablePlugin.php, add below code

<?php 
namespace Thecoachsmb\Productmodule\Plugin\Product\Type;

class ConfigurablePlugin
{
    public function afterGetUsedProductCollection(\Magento\ConfigurableProduct\Model\Product\Type\Configurable $subject, $result)
   {
       $result->addAttributeToSelect('description');
       return $result;
   }
}

Step 3: Update the product Description on swatches click

To change the product name, sku on swatches click, we will need to modifyΒ swatch-renderer.jsΒ file located inΒ Magento_Swatches/view/base/web/js/swatch-renderer.js. But in the core file we can not add the code. SoΒ To modify the js file, we need toΒ override js file in our module

Let’s override the js file now,

CreateΒ requirejs-config.js file in app/code/Thecoachsmb/Productmodule/view/frontend/

with the content as below:

var config = {
   map: {
      '*': {
         'Magento_Swatches/js/swatch-renderer':'Thecoachsmb_Productmodule/js/swatch-renderer'
      }
   }
};

CreateΒ swatch-renderer.jsΒ file in directory :Β app/code/Thecoachsmb/Productmodule/view/frontend/web/js/

Copy the code fromΒ vendor/magento/module_swatches/view/base/web/js/swatch-renderer.jsΒ to our moduleΒ Β swatch-renderer.js.

In the functionΒ _OnClick: function ($this, $widget)

add below lines:

var productName = this.options.jsonConfig.names[this.getProduct()];
if(productName) {
   $('[data-ui-id="page-title-wrapper"]').html(productName);
}

as shown below:-

This will update the product name on swatches click for configurable product.

For Product sku update, use below code:

var productSku = this.options.jsonConfig.skus[this.getProduct()];
if(productSku) {
$('.product-info-stock-sku .sku .value').html(productSku);
}

For product description update on swatches click;-

var productDescription = this.options.jsonConfig.desc[this.getProduct()];
if (productDescription) {
$('#description .description .value').html(productDescription);
}

 

Run below commads:

php bin/magento se:up && php bin/magento se:s:d -f && php bin/magento c:f

That’s it. In this way. you can update the other information of the product as well.

Do comment your feedback !!