How to switch Product SKU according to the selection of child products in Magento 2

How to switch product SKU according to the selection of child products in Magento 2

While buying a pair of shoes, you have to select several options before making a purchase like a shoe size, color or some other options too. It’s not a typical shoppable thing where you just add the product to cart and make payment because of its configurable product. Over time, these configurable products are becoming popular because it allows customers to select the variant they love to buy.

Magento allows the store owner to create and sell such type of products using backend options. But creating such configurable product required setting up several options such as size, color, model, make, etc. Because Magento treats this configurable product as a set of simple products. Each variation of the product has its own SKU and inventory system.

On the frontend, whenever a user picks a convenient option from the configurable product, product options and price will be changed accordingly but not product SKU in default Magento store environment. To get the child product SKU from the configurable product, here is another blog to switch product SKU according to the selection of child products in Magento 2.

To do the same, first we need to create “di.xml” file in following path using below code.

app\code\Vendor\Extension\etc\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="Vendor_Extension_Plugin_ConfigurableProduct_Block_Product_View_Type_Configurable" sortOrder="10" type="Vendor\Extension\Plugin\ConfigurableProduct\Block\Product\View\Type\Configurable"/>
    </type>
 
    <type name="Magento\Swatches\Block\Product\Renderer\Configurable">
        <plugin  name="Vendor_Extension_ConfigurableSkuSwitch_Plugin_Magento_Swatches_Block_Product_Renderer_Configurable" sortOrder="10" type="Vendor\Extension\Plugin\Swatches\Block\Product\Renderer\Configurable"/>
    </type>
</config>

Now, we have to create “Configurable.php” file at following path using below code.

app\code\Vendor\Extension\Plugin\ConfigurableProduct\Block\Product\View\Type\Configurable.php

<?php 
namespace Vendor\Extension\Plugin\ConfigurableProduct\Block\Product\View\Type; 

class Configurable 
{ 
	public function afterGetJsonConfig( 
		\Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject, $result 
	) { 
		$jsonResult = json_decode($result, true); 
		$jsonResult['skus'] = []; 
		foreach ($subject->getAllowProducts() as $simpleProduct) {
            		$jsonResult['skus'][$simpleProduct->getId()] = $simpleProduct->getSku();
		}
    		$result = json_encode($jsonResult);
        	return $result;
	}
}

Now, we have to create Configurable.php file at following path using below code.

app\code\Vendor\Extension\Plugin\Swatches\Block\Product\Renderer\Configurable.php

<?php 
namespace Vendor\Extension\Plugin\Swatches\Block\Product\Renderer; 
class Configurable 
{ 
	public function afterGetJsonConfig(
		\Magento\Swatches\Block\Product\Renderer\Configurable $subject, $result
	) { 
		$jsonResult = json_decode($result, true); 
		$jsonResult['skus'] = []; 
		foreach ($subject->getAllowProducts() as $simpleProduct) {
           		$jsonResult['skus'][$simpleProduct->getId()] = $simpleProduct->getSku();
        	}
        	$result = json_encode($jsonResult);
        	return $result;
	}
}

In this code, we have defined “skuswitch.js” and “swatch-skuswitch.js” which we are required and we create in later step.

var config = {
    config: {
        mixins: {
            'Magento_ConfigurableProduct/js/configurable': {
                'Vendor_Extension/js/model/skuswitch': true
            },
            'Magento_Swatches/js/swatch-renderer': {
                'Vendor_Extension/js/model/swatch-skuswitch': true
            }
        }
	}
};

In this last step, we have to “skuswitch.js” using below code at this path.

app\code\Vendor\Extension\view\frontend\web\js\model\skuswitch.js

    define([
    'jquery',
    'mage/utils/wrapper'
], function ($, wrapper) {
	'use strict';
 
    return function(targetModule){
 
        var reloadPrice = targetModule.prototype._reloadPrice;
        var reloadPriceWrapper = wrapper.wrap(reloadPrice, function(original){
        var result = original();
        var simpleSku = this.options.spConfig.skus[this.simpleProduct];
 
            if(simpleSku != '') {
                $('div.product-info-main .sku .value').html(simpleSku);
            }
            return result;
        });
        targetModule.prototype._reloadPrice = reloadPriceWrapper;
        return targetModule;
	};
});

Now, we need to create remaining “swatch-skuswitch.js” file at below location.

app\code\Vendor\Extension\view\frontend\web\js\model\swatch-skuswitch.js

define([
    'jquery',
    'mage/utils/wrapper'
], function ($, wrapper) {
	'use strict';
 
    return function(targetModule){
        var updatePrice = targetModule.prototype._UpdatePrice;
        targetModule.prototype.configurableSku = $('div.product-info-main .sku .value').html();
        var updatePriceWrapper = wrapper.wrap(updatePrice, function(original){
            var allSelected = true;
            for(var i = 0; i<this.options.jsonConfig.attributes.length;i++){
                if (!$('div.product-info-main .product-options-wrapper .swatch-attribute.' + this.options.jsonConfig.attributes[i].code).attr('option-selected')){
                	allSelected = false;
                }
            }
            var simpleSku = this.configurableSku;
            if (allSelected){
                var products = this._CalcProducts();
                simpleSku = this.options.jsonConfig.skus[products.slice().shift()];
            }
            $('div.product-info-main .sku .value').html(simpleSku);
              return original();
        });
 
        targetModule.prototype._UpdatePrice = updatePriceWrapper;
        return targetModule;
	};
});

And that’s it! Now product SKU will be changed dynamically based on the customer selection. Also, You can use this code according to your need for changing Product SKU.
If you need any help regarding this code, simply leave a comment below and don’t forget to smash that stars if you found this blog helpful.
Happy Coding!

Previous Article

How to Change Order PDF Format in Magento 2

Next Article

How to Expand default Layered Navigation Category Filters in Magento 2

Write a Comment
  1. Trayan Grigorov

    Great tutorial. Works as a charm on Magento 2.3.3. I changed the getSku() function with getAttributeText(‘custom_attribute’) in order to get the value of a custom attribute. So with some modification, you can show custom attribute of a simple product on the page of a configurable product when the simple product is called with a swatch or a drop down. Good work!

  2. Trayan Grigorov

    Great tutorial. Works as a charm on Magento 2.3.3. I changed the getSku() function with getAttributeText(‘custom_attribute’) in order to get the value of a custom attribute. So with some modification, you can show custom attribute of a simple product on the page of a configurable product when the simple product is called with a swatch or a drop down. Good work!

    1. Jigar Dhaduk

      Hello Trayan,
      Could you please reply with that snippet in which child product’s custom option will display?
      I have done it by ajax+jquery, but the custom options are not saved when we do add to cart.
      Waiting for your reply.

  3. Stefan Heule

    How would one prevent displaying the sku of the configurable product and only show the simple product skus when they are selected?

    1. You need to find the file which shows the default SKU when product page load, and you need to apply the logic there that if this is configurable product then it now shows the SKU.

  4. Jigar Dhaduk

    Hello Dhiren,
    Is there any way to display child product’s custom options while changing the swatches/dropdown value on the configurable products?
    It would be great if you comment regarding this.

    1. There is no any specific way for this one, but you can do something like, when it changes, you can fetch the data using ajax call and show on that page.

  5. Hello Dhiren,

    I have a query and I am hopeful you might be able to help me with this. We are in the process of developing a jewellery e-commerce website. We will have to give certain customization options for gold purity/diamond quality. So when a user selects a certain metal/diamond quality, we are able to change the price dynamically on the front end but how can we get the attribute details like metal weight, diamond grade, etc. changed dynamically on the front end when a user selects from one of the options provided?

    It would be really helpful if you could advise us on the same.

  6. Hi,

    I am using magento version 2.3.5
    I have tried above code with the given path
    Its not working
    pls provide solution

    1. Hi
      Please confirm you have created other required files of the custom extension. The extension is enabled and installed properly.
      Also, confirm if it’s not conflicting with other extensions.

  7. Aysar Ishtaiwi

    I applied this code but it didn’t work
    product options are not displayed and this error occurs:
    Uncaught TypeError: Cannot read property ‘_UpdatePrice’ of undefined
    at swatch-skuswitch.js:8

  8. Manbear Duncan

    In 2.4 the selected option no longer has an “option-selected” attribute. Instead of checking for the attr, I check if the element hasClass(‘selected’) and the code works as expected. Thank you for this snippet!

    1. You could also change this line in swatch-skuswitch.js:
      this.options.jsonConfig.attributes[i].code).attr(‘option-selected’))

      to

      this.options.jsonConfig.attributes[i].code).attr(‘data-option-selected’))

      1. It worked with Magento Open Source 2.4.3 with a little change mentioned above. Used the below code instead of attribute ‘option-selected’

        this.options.jsonConfig.attributes[i].code).attr(‘data-option-selected’)

        Thank you so much

  9. I’m getting “Plugin class ***\***\Plugin\ConfigurableProduct\Block\Product\View\Type\Configurable doesn’t exist” when the path is correct

  10. Malai Prakash Kaliraj

    I had been tried to chang sku number in existing product, saved it, then I tried to replace the older sku again in the same product it is not working, how to replace the old sku

  11. Jatin Kamlani

    Hello
    I have to hide magento default price and show my custom price and i am using this module for configurable product, for dropdown it working Properly but for swatches it is not working, may be due to update price function because i have hided price, so is there any other solution?? Or any other function which i use for swatches please help me

  12. Trying to use this for color swatch swapping but not seeing the SKU change. I did have to delete the di.xml file to get setup:upgrade to run as 2.3.7 was not happy with a blank file. Any suggestions?

  13. Is this article still correct? The formatting doesn’t look right. Especially the “app\code\Vendor\Extension\etc\di.xml” code.

  14. Hi,

    I don;t understand where you place the bellow code:
    var config = {
    config: {
    mixins: {
    ‘Magento_ConfigurableProduct/js/configurable’: {
    ‘Vendor_Extension/js/model/skuswitch’: true
    },
    ‘Magento_Swatches/js/swatch-renderer’: {
    ‘Vendor_Extension/js/model/swatch-skuswitch’: true
    }
    }
    }
    };
    Thanks in advance

    Kostas

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨