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!
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!
Tryan can u show your code for custom_attribute?
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!
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.
How would one prevent displaying the sku of the configurable product and only show the simple product skus when they are selected?
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.
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.
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.
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.
Contact us on support@magecomp.com
Hi,
I am using magento version 2.3.5
I have tried above code with the given path
Its not working
pls provide solution
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.
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
You can just create other required files of the module same as core modules.
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!
Mind sharing the rest of the module files mentioned in some reply below?
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’))
I tried but this did not work with Magento 2.4.3
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
Yes, you may need to modify the code according to Magento version changes.
Still does not work
Please specify which issue you are facing?
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.
Can I modify this so the name changes instead of the sku?
Yes, you will need to customize the code accordingly.
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
Make sure you have run all the Magento default commands including caching and indexing.
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.
This Post seems not to work with Magento 2.4.6? Any ideas?
According to the Magento version change, may be file changes needed accordingly.
It worked for me perfectly. I used it for v2.4.4. Thanks.
I used it for Magento v2.4.4 and it worked Without any errors or mistakes. Thanks.
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?
As you are using the latest version, you have to use updated code accordingly.
We tried this in Magento 2.4.4 with Hyva theme but it is not working.
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
Is this article still correct? The formatting doesn’t look right. Especially the “app\code\Vendor\Extension\etc\di.xml” code.
Thanks for bringing it to our notice. We have updated the blog now.
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
You need to create that file into following location
app\code\Vendor\Extension\view\frontend\requirejs-config.js