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.

answered Oct 21, 2019 at 9:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.