Blog

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

Do you want to change the product name, sku 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.

In this article, we are going to 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 Name 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>
</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();
       }

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

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

Step 3: Update the product Name 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);
}

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 you want to update the description also, then follow this article.

Do comment your feedback !!

8 thoughts on “How to change product name dynamically in configurable product when click swatches Magento2

  1. hi madam, i am trying add code above for change configuration product description. i am follow all step your provide but not working so please help me.

  2. Hi Mam i have facing some in magento 2.4.1 for configurable item .
    I want to show and clickable also price quantity update on select swatches option of out of stock item which one associated with configurable .
    i have uses lot of extention but not getting all , even option show now but price not show correct when select the option also need add to cart button disable for out of stock option ,
    Please give me sum suggetion how to do this .
    Note:(User check all option and price even product out of stock or in stock )

    Thanks
    Mkumar

Leave a Reply

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

πŸš€ Let’s Connect on LinkedIn! πŸš€

Want to level up your skills and knowledge? πŸš€
Follow us on LinkedIn to get:
βœ… Expert insights on business growth
βœ… Daily tips to sharpen your skills
βœ… Exclusive updates from The Coach SMB

Let's grow together!