0

How to change product name dynamically in configurable product when click swatches Magento 2.3

I followed the provided code in above link with help of a programmer by mistake I deleted etc folder I managed to get env.php and. rest of the file from backup which I had before adding the above code but my website was not working then I deleted 'custom_layout_update_file' now website working but I can't see configurable product any help would appreciate


enter image description here

Please see the attached error coming in the console but can't see configurable product only parent product We can see.

1
  • I add a couple of configurable products but it's just showing me parent product only no child product and when I tried to add parent product in cart it's giving me the error you need to choose the option for your item.Simple product is wroking fine in my website i can easily add into cart any help would appreciate. Nov 11, 2020 at 16:15

2 Answers 2

0

Module Method Working For me in Magento 2.1 / 2.2 /2.3 :: The below Code is to change Name & Description both. For Magento 2.4 add mixin


1. app/code/[VendorName]/[ModuleName]/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '[VendorName_ModuleName]',
    __DIR__
);

2. app/code/[VendorName]/[ModuleName]/etc/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="[VendorName_ModuleName]" setup_version="1.0.0" />
</config>

3. app/code/[VendorName]/[ModuleName]/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="[VendorName_ModuleName]-product-block" type="[VendorName]\[ModuleName]\Plugin\Product\View\Type\ConfigurablePlugin" sortOrder="1" />
    </type>
    <type name="Magento\ConfigurableProduct\Model\Product\Type\Configurable">
        <plugin name="[VendorName_ModuleName]-product-model" type="[VendorName]\[ModuleName]\Plugin\Product\Type\ConfigurablePlugin" sortOrder="1" />
    </type>
</config>

4. app/code/[VendorName]/[ModuleName]/Plugin/Product/Type/ConfigurablePlugin.php

<?php 
namespace [VendorName]\[ModuleName]\Plugin\Product\Type;

    class ConfigurablePlugin
    {
        public function afterGetUsedProductCollection(\Magento\ConfigurableProduct\Model\Product\Type\Configurable $subject, $result)
        {
            $result->addAttributeToSelect('name');
            $result->addAttributeToSelect('description');
            return $result;
        }
    }

5. app/code/[VendorName]/[ModuleName]/Plugin/Product/View/Type/ConfigurablePlugin.php

<?php 

namespace [VendorName]\[ModuleName]\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->getDescription()) {
            $result['productDescription'] = $currentProduct->getDescription();
        }
        if ($currentProduct->getSku()) {
            $result['productSku'] = $currentProduct->getSku();
        }
        foreach ($subject->getAllowProducts() as $product) {
            $result['names'][$product->getId()][] =
                [
                    'name' => $product->getData('name'),
                ];
            $result['descriptions'][$product->getId()][] =
                [
                    'description' => $product->getData('description'),
                ];
            $result['skus'][$product->getId()][] =
                [
                    'sku' => $product->getData('sku'),
                ];
        }
        return $this->jsonEncoder->encode($result);
    }
}

6. app/code/[VendorName]/[ModuleName]/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'Magento_Swatches/js/swatch-renderer':'[VendorName]_[ModuleName]/js/swatch-renderer'
        }
    }
};

7. app/code/[VendorName]/[ModuleName]/view/frontend/web/js/swatch-renderer.js

Copy original JS file(vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js & Replace _OnClick function with below code (Line No Approx: 712)

_OnClick: function ($this, $widget, eventName) {
            var $parent = $this.parents('.' + $widget.options.classes.attributeClass),
                $wrapper = $this.parents('.' + $widget.options.classes.attributeOptionsWrapper),
                $label = $parent.find('.' + $widget.options.classes.attributeSelectedOptionLabelClass),
                attributeId = $parent.attr('attribute-id'),
                $input = $parent.find('.' + $widget.options.classes.attributeInput);

            if ($widget.inProductList) {
                $input = $widget.productForm.find(
                    '.' + $widget.options.classes.attributeInput + '[name="super_attribute[' + attributeId + ']"]'
                );
            }

            if ($this.hasClass('disabled')) {
                return;
            }

            if ($this.hasClass('selected')) {
                $parent.removeAttr('option-selected').find('.selected').removeClass('selected');
                $input.val('');
                $label.text('');
                $this.attr('aria-checked', false);
            } else {
                $parent.attr('option-selected', $this.attr('option-id')).find('.selected').removeClass('selected');
                $label.text($this.attr('option-label'));
                $input.val($this.attr('option-id'));
                $input.attr('data-attr-name', this._getAttributeCodeById(attributeId));
                $this.addClass('selected');
                $widget._toggleCheckedAttributes($this, $wrapper);

                /* CUSTOM CODE START */
                if (jQuery('[data-ui-id="page-title-wrapper"]').length && this.options.jsonConfig.names) {
                    if (this.getProduct()) {
                        var iname = this.options.jsonConfig.names[this.getProduct()][0].name
                        if (iname != '') {
                            jQuery('[data-ui-id="page-title-wrapper"]').html(iname);
                        }
                    }
                    else {
                        var productName = this.options.jsonConfig.productName
                        if (productName) {
                            jQuery('[data-ui-id="page-title-wrapper"]').html(productName);
                        }
                    }
                }
                if (jQuery('.description > div.value').length && this.options.jsonConfig.descriptions) {
                    if (this.getProduct()) {
                        var description = this.options.jsonConfig.descriptions[this.getProduct()][0].description
                        if (description) {
                            jQuery('.description > div.value').html(description);
                        }
                    } else {
                        var productDescription = this.options.jsonConfig.productDescription
                        if (productDescription) {
                            jQuery('.description > div.value').html(productDescription);
                        }
                    }
                }
                /* CUSTOM CODE END */

                $widget._Rebuild();

                if ($widget.element.parents($widget.options.selectorProduct)
                    .find(this.options.selectorProductPrice).is(':data(mage-priceBox)')
                ) {
                    $widget._UpdatePrice();
                }

                $widget._loadMedia(eventName);
                $input.trigger('change');
            }
        },

For Magento 2.4

For mixins you have to Add or Update app/code/[VendorName]/[ModuleName]/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            "Magento_Swatches/js/swatch-renderer" : {
                "[VendorName]_[ModuleName]/js/swatch-renderer": true
            }
        }
    }
};

For mixins you have to Add or Update app/code/[VendorName]/[ModuleName]/view/frontend/web/js/swatch-renderer.js

define([
    'jquery',
    'underscore',
    'jquery/ui',
    'jquery/jquery.parsequery'
], function ($, _) {
    'use strict';
    return function (widget) {

        $.widget('mage.SwatchRenderer', widget, {

            /**
             * Event for swatch options
             *
             * @param {Object} $this
             * @param {Object} $widget
             * @private
             */
            _OnClick: function ($this, $widget) {

                $widget._super($this, $widget);

                $widget._UpdateDetailProduct();

            },

            /**
             * Event for select
             *
             * @param {Object} $this
             * @param {Object} $widget
             * @private
             */
            _OnChange: function ($this, $widget) {

                $widget._super($this, $widget);

                $widget._UpdateDetailProduct();

            },

            _UpdateDetailProduct: function () {
                var $widget = this,
                    index = '',
                    options = _.object(_.keys($widget.optionsMap), {}),
                    childProductName = this.options.jsonConfig.names,
                    childProductDescription = this.options.jsonConfig.descriptions;
                    childProductSku = this.options.jsonConfig.skus;

                $widget.element.find('.' + $widget.options.classes.attributeClass + '[data-option-selected]').each(function () {
                    var attributeId = $(this).attr('data-attribute-id');
                    options[attributeId] = $(this).attr('data-option-selected');
                });

                /* CUSTOM CODE START */
                if (jQuery('[data-ui-id="page-title-wrapper"]').length && this.options.jsonConfig.names) {
                    
                    if (this.getProduct()) {
                        var iname = this.options.jsonConfig.names[this.getProduct()][0].name
                        if (iname != '') {
                            jQuery('[data-ui-id="page-title-wrapper"]').html(iname);
                        }
                    }
                    else {
                        var productName = this.options.jsonConfig.productName
                        if (productName) {
                            jQuery('[data-ui-id="page-title-wrapper"]').html(productName);
                        }
                    }
                }
                if (jQuery('.description > div.value').length && this.options.jsonConfig.descriptions) {
                    if (this.getProduct()) {
                        var description = this.options.jsonConfig.descriptions[this.getProduct()][0].description
                        if (description) {
                            jQuery('.description > div.value').html(description);
                        }
                    } else {
                        var productDescription = this.options.jsonConfig.productDescription
                        if (productDescription) {
                            jQuery('.description > div.value').html(productDescription);
                        }
                    }
                }
                var simpleSku = this.options.jsonConfig.skus[this.getProduct()][0].sku;

                if(simpleSku != '') {
                    $('div.product-info-main .sku .value').html(simpleSku);
                }
                /* CUSTOM CODE END */
            },
        });
        return $.mage.SwatchRenderer;
    }
});

** Output::** enter image description here

0

For shops, which are using a Hyvä Theme, our module might be an option:

https://commercemarketplace.adobe.com/customgento-module-child-product-data.html

This updates the following attributes quick and easy:

  • Product Name
  • SKU
  • Short Description
  • Description
  • “More Information” Block
  • Related Products (performantly via AJAX)
  • Upsell Products (performantly via AJAX)

You only need to enter the fitting identifiers of your Hyvä theme in the system configuration, and the module will do the rest.

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.