Magento 2 how to add images to recently ordered / reorder products block in the sidebar
La solution
To add images to the reorder block we should provide them to knockout
Override Magento\Sales\CustomerData\LastOrderedItems in a custom module, change the items array in the getItems method to include an image:
$items[] = [
'id' => $item->getId(),
'name' => $item->getName(),
'url' => $url,
'is_saleable' => $this->isItemAvailableForReorder($item),
'image' => $this->getImageData($product)
];
And a method to generate the image data (adapted from wishlist):
protected function getImageData($product)
{
/*Set variant product if it is configurable product.
It will show variant product image in sidebar instead of configurable product image.*/
$simpleOption = $product->getCustomOption('simple_product');
if ($simpleOption !== null) {
$optionProduct = $simpleOption->getProduct();
$product = $optionProduct;
}
/** @var \Magento\Catalog\Helper\Image $helper */
$helper = $this->imageHelperFactory->create()
->init($product, 'wishlist_sidebar_block');
$template = $helper->getFrame()
? 'Magento_Catalog/product/image'
: 'Magento_Catalog/product/image_with_borders';
try {
$imagesize = $helper->getResizedImageInfo();
} catch (NotLoadInfoImageException $exception) {
$imagesize = [$helper->getWidth(), $helper->getHeight()];
}
$width = $helper->getFrame()
? $helper->getWidth()
: $imagesize[0];
$height = $helper->getFrame()
? $helper->getHeight()
: $imagesize[1];
return [
'template' => $template,
'src' => $helper->getUrl(),
'width' => $width,
'height' => $height,
'alt' => $helper->getLabel(),
];
}
Then we override module-sales/view/frontend/templates/reorder/sidebar.phtml to include the image:
<a class="product-item-photo" data-bind="attr: { href: url, title: name }">
<!-- ko template: {name: $data.image.template, data: $data.image} --><!-- /ko -->
</a>
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange