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?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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.