Magento 2 – Update Product Price via Swatches on Custom Page

magento2priceproductswatches

On a custom page I want to show only the swatches of a configurable product and automatically update the product price based on the chosen swatches.

I managed to get the swatches and price to show up on the page, but I can't get the price to update automatically.

My custom page layout:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="empty" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Magento_Swatches::css/swatches.css"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Company\Module\Block\FormBlock" name="iframe.form" template="Company_Module::form.phtml" cacheable="false">
                <block class="Magento\Catalog\Block\Product\View" name="product.info.options.wrapper" as="product_options_wrapper" template="Magento_Catalog::product/view/options/wrapper.phtml">
                    <block class="Magento\Swatches\Block\Product\Renderer\Configurable" name="product.info.options.swatches" as="swatch_options" before="-" />
                    <container name="product.info.price" label="Product info auxiliary container" htmlTag="div" htmlClass="product-info-price">
                        <block class="Magento\Catalog\Pricing\Render" name="product.price.final">
                            <arguments>
                                <argument name="price_render" xsi:type="string">product.price.render.default</argument>
                                <argument name="price_type_code" xsi:type="string">final_price</argument>
                                <argument name="zone" xsi:type="string">item_view</argument>
                            </arguments>
                        </block>
                    </container>
                </block>
            </block>
        </referenceContainer>
    </body>
</page>

The FormBlock extends Magento\Catalog\Block\Product\View, in the controller I set the 'product' registry to the product being viewed with $this->registry->register('product', $product);.

The form.phtml file simply calls <?= $block->getChildHtml() ?>.

Best Answer

in the js file Magento_Swatches/js/swatch-renderer.js you may follow this file in your browser console and put a break point right at the top of the function _OnClick (line 687 on Magento 2.2.5)

then you will notice the code does not reach the line that updates the price (see: $widget._UpdatePrice() at line 719)

now, to remedy, you may write a mixin that extends this script and if you can tweak the line that tries to find the priceselector

Or more simply you may also add a class 'product-info-main'. Once this class is added onto your iframe, the script should find the price.

I attach a screenshot for you to see the missing class by yourself

enter image description here

Related Topic