2

I have color swatches on related products list on product page. I want to change product image on the basis of swatch selection on view page.

How can I change image?

0

1 Answer 1

1

I have done this using below steps:

1. add a function in the block : vendor/module_name/Block/Index/Index.php

public function getProductPricetoHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null
    ) {
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');
        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product
            );
        }
        return $price;
    }

2. call your block in phtml and use action in the top of the file:

use Magento\Framework\App\Action\Action;
$blockObj= $block->getLayout()->createBlock('Vendor\Module_Name\Block\Index\Index');

3. call price block like this for product price:

<?php echo $blockObj->getProductPricetoHtml($product, $type); ?>

4. Call color swatches:

<?php if($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE){
                                     $swatchBlock = $this->getLayout()->createBlock("Magento\Swatches\Block\Product\Renderer\Listing\Configurable")->setTemplate("Magento_Swatches::product/listing/renderer.phtml");
                                       echo $swatchBlock->setProduct($product)->toHtml();                           
                                    } ?>

Done! now product image will change on click swatches on any custom product collection.

I hope it will be helpful someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.