Magento 2 – Change Product Name Dynamically in Configurable Product View

configurable-productmagento-2.1magento2PHPproduct

How I can change my configurable product name and description dynamically when one option is selected, right now is change only the image, I need to do the same with the name and description.

HTML structure:

<div class="product media">
    <div class="product attribute description">
        <div class="value">
            <p>text description.</p>
        </div>
    </div>
</div>

enter image description here

Best Answer

You can try below custom module and modify according to your requirement.

app/code/Anshu/SCdata/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Anshu_SCdata',
    __DIR__
);

app/code/Anshu/SCdata/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="Anshu_SCdata" setup_version="1.0.0">
            <sequence>
                <module name="Magento_Swatches"/>
            </sequence>
        </module>
    </config>

app/code/Anshu/SCdata/etc/frontend/di.xml

<?xml version="1.0" encoding="UTF-8"?>
    <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="anshu_configurable_product_configurable"
                    type="Anshu\SCdata\Block\ConfigurableProduct\Product\View\Type\Configurable"
                    sortOrder="1"/>
        </type>
    </config>

app/code/Anshu/SCdata/Block/ConfigurableProduct/Product/View/Type/Configurable.php

<?php

namespace Anshu\SCdata\Block\ConfigurableProduct\Product\View\Type;

use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Json\DecoderInterface;

class Configurable
{
    protected $jsonEncoder;
    protected $jsonDecoder;
    protected $_productRepository;

    public function __construct(
            \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
            EncoderInterface $jsonEncoder,
            DecoderInterface $jsonDecoder
    ) {
        $this->jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
        $this->_productRepository = $productRepository;
    }

    public function getProductById($id)
    {
        return $this->_productRepository->getById($id);
    }

    public function aroundGetJsonConfig(
        \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject,
        \Closure $proceed
    )
    {
        $sname = [];
        $sdescription = [];

        $config = $proceed();
        $config = $this->jsonDecoder->decode($config);

        foreach ($subject->getAllowProducts() as $prod) {
            $id = $prod->getId();
            $product = $this->getProductById($id);
            $sname[$id] = $product->getName();
            $sdescription[$id] = $product->getDescription();
        }
        $config['sname'] = $sname;
        $config['sdescription'] = $sdescription;

        return $this->jsonEncoder->encode($config);
    }
}

app/code/Anshu/SCdata/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'Magento_Swatches/js/swatch-renderer' : 'Anshu_SCdata/js/swatch-renderer',
            'magento-swatch.renderer' : 'Magento_Swatches/js/swatch-renderer',
        }
    }
};

app/code/Anshu/SCdata/view/frontend/web/js/swatch-renderer.js

define([
  'jquery',
  'jquery/ui',
  'magento-swatch.renderer'
], function($){

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

        /**
         * Event for swatch options
         *
         * @param {Object} $this
         * @param {Object} $widget
         * @private
         */
        _OnClick: function ($this, $widget) {
            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);
            }

            $widget._Rebuild();

            // Custom Code starts
            var iname = $widget.options.jsonConfig.sname[this.getProduct()];
            var idescription = $widget.options.jsonConfig.sdescription[this.getProduct()];

            if(idescription != ''){
                $('[data-role="content"]').find('.description .value').html(idescription);
            }
            if(iname != ''){
                $('[data-ui-id="page-title-wrapper"]').html(iname);
            }
            // Custom code ends

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

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

    });

  return $.anshu.SwatchRenderer;
});
Related Topic