0

i'm trying to update price when i change swatches in catalog.

I find this solution :

from https://github.com/magento/magento2/issues/3150

app/design/CUSTOM/THEME/Magento_Swatches/templates/product/listing/renderer.phtml

require(["jquery", "jquery/ui", "Magento_Swatches/js/swatch-renderer"], function ($) {         
        $('.swatch-opt-<?php /* @escapeNotVerified */ echo $block->getProduct()->getId() ?>').SwatchRenderer({
            selectorProduct: '.product-item-details',
            onlySwatches: true,
            enableControlLabel: false,
            numberToShow: <?php /* @escapeNotVerified */ echo $block->getNumberSwatchesPerProduct(); ?>,
            jsonConfig: <?php /* @escapeNotVerified */ echo $block->getJsonConfig(); ?>,
            jsonSwatchConfig: <?php /* @escapeNotVerified */ echo $block->getJsonSwatchConfig(); ?>,
            mediaCallback: '<?php /* @escapeNotVerified */ echo $block->getMediaCallback() ?>'
        });
    }); 

to

require(["jquery", "jquery/ui","priceBox", "Magento_Swatches/js/swatch-renderer"], function ($) {
         var dataPriceBoxSelector = '[data-role=priceBox]',
            dataProductIdSelector = '[data-product-id=<?php echo $block->getProduct()->getId()?>]',
            priceBoxes = $(dataPriceBoxSelector + dataProductIdSelector);

        priceBoxes = priceBoxes.filter(function(index, elem){
            return !$(elem).find('.price-from').length;
        });

        priceBoxes.priceBox();
        $('.swatch-opt-<?php /* @escapeNotVerified */ echo $block->getProduct()->getId() ?>').SwatchRenderer({
            selectorProduct: '.product-item-details',
            onlySwatches: true,
            enableControlLabel: false,
            numberToShow: <?php /* @escapeNotVerified */ echo $block->getNumberSwatchesPerProduct(); ?>,
            jsonConfig: <?php /* @escapeNotVerified */ echo $block->getJsonConfig(); ?>,
            jsonSwatchConfig: <?php /* @escapeNotVerified */ echo $block->getJsonSwatchConfig(); ?>,
            mediaCallback: '<?php /* @escapeNotVerified */ echo $block->getMediaCallback() ?>'
        });
    });

But as you can read in the post, it don't update price. So hopefully someone find how to do it :

Your solutions works @johnny-longneck. For the price format this is what I did:

Instead of initializing the priceBox object on template file like:

priceBoxes.priceBox();

Pass the priceBox object as a parameter for SwatchRenderer

priceBox: priceBoxes

Then add the option to yout swatch-render.js constructor:

priceBox: false,

And then just initialize the priceBox at the beginning of the _UpdatePrice method:

var $widget = this; $widget.options.priceBox.priceBox();

Hope it helps to someone !!

Ok, i try to do it but it don't work. Can someone sho me where exactly put this code ? thanks !

1 Answer 1

1

Steps for update price:-

app/design/CUSTOM/THEME/Magento_Swatches/templates/product/listing/renderer.phtml

require(["jquery", "jquery/ui","priceBox", "Magento_Swatches/js/swatch-renderer"], function ($) {
         var dataPriceBoxSelector = '[data-role=priceBox]',
                dataProductIdSelector = '[data-product-id=<?php echo $block->getProduct()->getId() ?>]',
                priceBoxes = $(dataPriceBoxSelector + dataProductIdSelector);



    priceBoxes = priceBoxes.filter(function (index, elem) {
        return !$(elem).find('.price-from').length;
    });
    priceBoxes.priceBox({'priceConfig': <?php /* @escapeNotVerified */ echo $block->getJsonConfigPrice(); ?>});
    $('.swatch-opt-<?php /* @escapeNotVerified */ echo $block->getProduct()->getId() ?>').SwatchRenderer({
        selectorProduct: '.product-item-details',
        onlySwatches: true,
        enableControlLabel: false,
        numberToShow: <?php /* @escapeNotVerified */ echo $block->getNumberSwatchesPerProduct(); ?>,
        jsonConfig: <?php /* @escapeNotVerified */ echo $block->getJsonConfig(); ?>,
        jsonSwatchConfig: <?php /* @escapeNotVerified */ echo $block->getJsonSwatchConfig(); ?>,
        mediaCallback: '<?php /* @escapeNotVerified */ echo $block->getMediaCallback() ?>'
    });
});

and overrite

Magento/Swatches/Block/Product/Renderer/Listing/Configurable.php

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace [Namespace]\[Vendor]\Block\Product\Renderer\Listing;

use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Helper\Product as CatalogProduct;
use Magento\ConfigurableProduct\Helper\Data;
use Magento\ConfigurableProduct\Model\ConfigurableAttributeData;
use Magento\Customer\Helper\Session\CurrentCustomer;
use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\Stdlib\ArrayUtils;
use Magento\Store\Model\ScopeInterface;
use Magento\Swatches\Helper\Data as SwatchData;
use Magento\Swatches\Helper\Media;
use Magento\Swatches\Model\Swatch;
use Magento\Framework\App\ObjectManager;
use Magento\Swatches\Model\SwatchAttributesProvider;
/**
 * Swatch renderer block in Category page
 *
 * @codeCoverageIgnore
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Configurable extends \Magento\Swatches\Block\Product\Renderer\Listing\Configurable
{
        /**
     * @var \Magento\Framework\Locale\FormatInterface
     */


protected $_localeFormat;

protected $_jsonEncoder;

public function __construct(
    Context $context,
    ArrayUtils $arrayUtils,
    EncoderInterface $jsonEncoder,
    Data $helper,
    CatalogProduct $catalogProduct,
    CurrentCustomer $currentCustomer,
    PriceCurrencyInterface $priceCurrency,
    ConfigurableAttributeData $configurableAttributeData,
    SwatchData $swatchHelper,
    Media $swatchMediaHelper,
    \Magento\Framework\Locale\FormatInterface $localeFormat,
    array $data = [],
    SwatchAttributesProvider $swatchAttributesProvider = null
) {
    $this->_localeFormat = $localeFormat;
    $this->_jsonEncoder =  $jsonEncoder;
    $this->swatchHelper = $swatchHelper;
    $this->swatchMediaHelper = $swatchMediaHelper;
    $this->swatchAttributesProvider = $swatchAttributesProvider
        ?: ObjectManager::getInstance()->get(SwatchAttributesProvider::class);
    parent::__construct(
        $context,
        $arrayUtils,
        $jsonEncoder,
        $helper,
        $catalogProduct,
        $currentCustomer,
        $priceCurrency,
        $configurableAttributeData,
        $swatchHelper,
        $swatchMediaHelper,
        $data,
        $swatchAttributesProvider
    );
}

/**
 * @return string
 */
protected function getRendererTemplate()
{
    return $this->_template;
}

/**
 * Produce and return block's html output.
 *
 * @return string
 */
protected function _toHtml()
{
    $output = '';
    if ($this->isProductHasSwatchAttribute()) {
        $output = parent::_toHtml();
    }

    return $output;
}

/**
 * @deprecated
 * @return string
 */
protected function getHtmlOutput()
{
    $output = '';
    if ($this->isProductHasSwatchAttribute()) {
        $output = parent::getHtmlOutput();
    }

    return $output;
}

/**
 * @return array
 */
protected function getSwatchAttributesData()
{
    $result = [];
    $swatchAttributeData = parent::getSwatchAttributesData();
    foreach ($swatchAttributeData as $attributeId => $item) {
        if (!empty($item['used_in_product_listing'])) {
            $result[$attributeId] = $item;
        }
    }
    return $result;
}

/**
 * Composes configuration for js
 *
 * @return string
 */
public function getJsonConfig()
{
    $this->unsetData('allow_products');
    return parent::getJsonConfig();
}


  /**
 * Get JSON encoded configuration array which can be used for JS dynamic
 * price calculation depending on product options
 *
 * @return string
 */
public function getJsonConfigPrice()
{
    /* @var $product \Magento\Catalog\Model\Product */
    $product = $this->getProduct();

    if (!$this->hasOptions()) {
        $config = [
            'productId' => $product->getId(),
            'priceFormat' => $this->_localeFormat->getPriceFormat()
            ];
        return $this->_jsonEncoder->encode($config);
    }

    $tierPrices = [];
    $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList();
    foreach ($tierPricesList as $tierPrice) {
        $tierPrices[] = $this->priceCurrency->convert($tierPrice['price']->getValue());
    }
    $config = [
        'productId' => $product->getId(),
        'priceFormat' => $this->_localeFormat->getPriceFormat(),
        'prices' => [
            'oldPrice' => [
                'amount' => $this->priceCurrency->convert(
                    $product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue()
                ),
                'adjustments' => []
            ],
            'basePrice' => [
                'amount' => $this->priceCurrency->convert(
                    $product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount()
                ),
                'adjustments' => []
            ],
            'finalPrice' => [
                'amount' => $this->priceCurrency->convert(
                    $product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue()
                ),
                'adjustments' => []
            ]
        ],
        'idSuffix' => '_clone',
        'tierPrices' => $tierPrices
    ];

    $responseObject = new \Magento\Framework\DataObject();
    $this->_eventManager->dispatch('catalog_product_view_config', ['response_object' => $responseObject]);
    if (is_array($responseObject->getAdditionalOptions())) {
        foreach ($responseObject->getAdditionalOptions() as $option => $value) {
            $config[$option] = $value;
        }
    }



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

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.