Thursday, 6 February 2014

Magento change product image on view page to associated product image

Magento's configurable product does not load its associated product image when we change the attribute value. To change the image of the product respective to the selected attribute value i have used this code. Magento website also offers a wiki to achieve this, but its pretty old and its written for magento version 1.5 and below. Link to wiki

I have tested this code in recent magento version which is 1.8 and the most famous 1.7.

Here is the code.


Open template/catalog/product/view.phtml

and find the line var productAddToCartForm = new VarienForm('product_addtocart_form'); on the bottom of the page.

Add these code on top of that line.

var mainProductImgSrc = document.getElementById("image").src;
var assocIMG =

if ($_product->getTypeId() == "configurable") {
echo "{";
$associated_products = $_product->loadByAttribute('sku', $_product->getSku())->getTypeInstance()->getUsedProducts();
foreach ($associated_products as $assoc)
$dados[] = $assoc->getId().":'".($assoc->image == "no_selection" || $assoc->image == "" ? $this->helper('catalog/image')->init($_product, 'image', $_product->image)->resize(365,400) : $this->helper('catalog/image')->init($assoc, 'image', $assoc->image)->resize(365,400))."'";
} else {
$dados[] = "";
echo implode(',', $dados );
if ($_product->getTypeId() == "configurable") {
echo "}";



open js/varien/product.js and find the line

for (var i = 0; i < this.tierPrices.length; i++) {

and add the below given code above  this-> " }.bind(this)); " line.

//to change product image based on option select for configurable product
settings = $$('.super-attribute-select');
imgSrc = mainProductImgSrc;
   attributeId = element.attributeId;
   imgSrc = assocIMG[element.options[element.selectedIndex].config.products];
   $('image').src = imgSrc;


Your are done now. Do remember to select the base image for the associated product. If there is no image set for the associated product and when you change the option the configurable product image will be used instead.

No comments:

Post a Comment