I'm trying to add an alternative image for all config product images. To do so I extended Magento\Catalog\Block\Product\Image
. For some reason $product->getMediagalleryImages()
always returns the same gallery for all products in the collection though. Is this the correct way of loading a media gallery for a product in M2?
<?php
namespace Ac\Catalog\Block\Product;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Gallery\ReadHandler;
class Image extends \Magento\Catalog\Block\Product\Image
{
protected $_productModel;
protected $_galleryReadHandler;
public function __construct(
Context $context,
Product $productModel,
ReadHandler $galleryReadHandler,
array $data = []
) {
if (isset($data['template'])) {
$this->setTemplate($data['template']);
unset($data['template']);
}
parent::__construct($context, $data);
$this->_productModel = $productModel;
$this->_galleryReadHandler = $galleryReadHandler;
}
public function getSrcAlt(): string
{
$product = $this->_productModel->load($this->getProductId());
if (strpos($product->getTypeId(), 'configurable') === false) {
return '';
}
$i = 0;
$this->_galleryReadHandler->execute($product);
foreach ($product->getMediaGalleryImages() as $image) {
if (++$i < 2) continue;
return sprintf('data-src-alt="%s"', $image['url']);
}
return '';
}
}