Skip to content

Magento 2 - Come modificare dinamicamente il nome del prodotto nella pagina di visualizzazione dei prodotti configurabili

Isabela, parte di questo gruppo di lavoro, ci ha fatto il favore di scrivere questa cronaca poiché conosce molto bene l'argomento.

Soluzione:

Potete provare il seguente modulo personalizzato e modificarlo in base alle vostre esigenze.

app/code/Anshu/SCdata/registration.php

app/code/Anshu/SCdata/etc/module.xml

    
    
        
            
                
            
        
    

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


    
        
            
        
    

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

jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
        $this->_productRepository = $productRepository;
    }

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

    public function aroundGetJsonConfig(
        MagentoConfigurableProductBlockProductViewTypeConfigurable $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;
});

Provare il seguente modulo:

  1. app/code/[VendorName]/[ModuleName]/registrazione.php
  2. app/code/[VendorName]/[ModuleName]/etc/modulo.xml


    
        
            
        
    

  1. app/code/[VendorName]/[ModuleName]/etc/di.xml


    
        
    
    
        
    

  1. app/code/[VendorName]/[ModuleName]/Plugin/Product/Type/ConfigurablePlugin.php
addAttributeToSelect('description');
        return $result;
    }
}
  1. app/code/[VendorName]/[ModuleName]/Plugin/Product/View/Type/ConfigurablePlugin.php
jsonEncoder = $jsonEncoder;
        $this->jsonDecoder = $jsonDecoder;
    }

    public function afterGetJsonConfig(MagentoConfigurableProductBlockProductViewTypeConfigurable $subject, $result)
    {
        $result = $this->jsonDecoder->decode($result);
        $currentProduct = $subject->getProduct();
        if ($currentProduct->getDescription()) {
            $result['productDescription'] = $currentProduct->getDescription();
        }

        foreach ($subject->getAllowProducts() as $product) {
            $result['descriptions'][$product->getId()][] =
                [
                    'description' => $product->getData('description'),
                ];
        }

        return $this->jsonEncoder->encode($result);
    }
}
  1. app/code/[VendorName]/[ModuleName]/view/frontend/requirejs-config.js
var config = {
    map: {
        '*': {
            'Magento_Swatches/js/swatch-renderer':'[VendorName]_[ModuleName]/js/swatch-renderer'
        }
    }
};
  1. app/codice/[VendorName]/[ModuleName]/view/frontend/web/js/swatch-renderer.js
_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('.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');
},

Nota: Copiare il file JS originale (vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js) e incollarlo nel percorso sopra indicato e aggiornare la funzione di cui sopra (_OnClick) OPPURE si può personalizzare il codice JS in base alle proprie esigenze. In questo caso, si può anche usare minix per sovrascrivere la funzione JS.

Sezione recensioni e valutazioni



Utilizzate il nostro motore di ricerca

Ricerca
Generic filters

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.