Blog

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 !!

3 thoughts on “How to change product description dynamically in configurable product when click swatches Magento2

  1. first of all I would like to thank you for this post! unfortunately I have a problem with ConfigurablePlugin.php. The class does not add attributes to the this.options.jsonConfig object. I got error this.options.jsonConfig.names is undefined. Can you help me?

Leave a Reply

Your email address will not be published. Required fields are marked *