0

I want to get the product id on selecting the swatch option. for that, I have used the code given below. I am getting the error of "Cannot read properties of undefined (reading 'options')" as per the screenshot.

Error Screenshot:- https://i.stack.imgur.com/cAsgD.png

/app/code/Vendor/Module/view/frontend/templates/product/view/type/custom.phtml

<script type="text/javascript">
requirejs(['jquery','underscore'], function(jQuery,_){
jQuery(window).on('load',function(){
    jQuery( ".product-options-wrapper div" ).click(function() {
        selpro();
    });
});
function selpro () {
    var selected_options = {};
    jQuery('div.swatch-attribute').each(function(k,v){
                var attribute_id    = jQuery(v).attr('data-attribute-id');
                var option_selected = jQuery(v).attr('data-option-selected');
                if(!attribute_id || !option_selected){ return;}
                selected_options[attribute_id] = option_selected;
            });

    var product_id_index = jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index;
    var found_ids = [];

            jQuery.each(product_id_index, function(product_id,attributes){
                var productIsSelected = function(attributes, selected_options){
                    return _.isEqual(attributes, selected_options);
                }
                if(productIsSelected(attributes, selected_options)){
                    found_ids.push(product_id);
                }
            });
    
    // console.log(found_ids);

    if (found_ids.length) {
        var selected_product_id = found_ids[0];
        jQuery('.myli').css('display','none');
        jQuery('#div'+selected_product_id).toggle();
    }
}
});
</script> 
4
  • you need to change whole code. I will post answer soon. let me prepare it for you Jun 13, 2022 at 10:04
  • on which version you are working? Jun 13, 2022 at 10:06
  • I am using Magento 2.4.4 version. Jun 13, 2022 at 10:10
  • okay posting answer soon Jun 13, 2022 at 10:17

1 Answer 1

2

Following code work for me you can try it.

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 disabled="false" 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 disabled="false" name="Vendor_Extension_ConfigurableSkuSwitch_Plugin_Magento_Swatches_Block_Product_Renderer_Configurable" sortOrder="10" type=" Vendor \ Extension \Plugin\Swatches\Block\Product\Renderer\Configurable"/>
    </type>
</config>

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;
    }
}

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;
    }
}

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

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
            }
        }
    }
};

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;
    };
});

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('data-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;
    };
});

Note: this will update SKU on selection you can modify as per your need.

3
  • I want to get description of child products as well, but couldn't with the same approach as above. Please help me to get description too. I'm using Magento 2.4.5. Mar 21, 2023 at 3:57
  • Using above code are you able to get child sku? @JasvirSingh Mar 22, 2023 at 18:55
  • I got it by using \Magento\Catalog\Model\ProductFactory $_productFactory, $product = $this->_productFactory->create()->setStoreId(0)->load($simpleProduct->getId()); $product->getDescription(); Mar 27, 2023 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.