How To

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



 
    
        
    
 
    
        
    

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


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

app\code\Vendor\Extension\view\frontend\requirejs-config.js

In this code, we have defined “skuswitch.js” and “swatch-skuswitch.js” which we are required a 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!

Click to rate this post!
[Total: 67 Average: 4.1]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

    • Hyva theme have different structured compared to normal Magento theme. So if you have to implement this into Hyva, you need to do further customisation according to Hyva structure. For more information, you can contact on support@magecomp.com

  • 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?

  • 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

    • You have to identify the proper function which also works for Swatches and then need to do customization there as well.

  • 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

  • I'm getting "Plugin class ***\***\Plugin\ConfigurableProduct\Block\Product\View\Type\Configurable doesn't exist" when the path is correct

    • Please Confirm you are creating the file on the proper path and there is no Mistake in the class name or something.

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

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

3 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

5 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

5 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

6 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

7 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago