0

I can successfully display the configurable product image in order detail page with the following code.

/** @var  $block \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer */
$_item = $block->getItem();
$imageBuilder = $objectManager->create('\Magento\Catalog\Block\Product\ImageBuilder');
<span style="display: table-cell;"><?= $imageBuilder->setProduct($_item->getProduct())->setImageId('cart_page_product_thumbnail')->create()->toHtml(); ?></span>

But I want the image is the simple product one. Like if I buy the blue one, it shows the blue image I set in admin.

Thanks in advance.

s.w
  • 3
  • 3

1 Answers1

0

You have to load the simple product from sku field of sales_order_item and then you get simple product image.

<?php

/** @var  $block \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer */
$_item = $block->getItem();
$imageBuilder = $objectManager->create('\Magento\Catalog\Block\Product\ImageBuilder');

if($_item->getProductType() == 'configurable'){
    $productObject = $objectManager->get('Magento\Catalog\Model\Product');
    $simpleproduct = $productObject->loadByAttribute('sku', $_item->getSku());
?>
    <span style="display: table-cell;"><?= $imageBuilder->setProduct($simpleproduct)->setImageId('cart_page_product_thumbnail')->create()->toHtml(); ?></span>
<?php
}else{

?>
<span style="display: table-cell;"><?= $imageBuilder->setProduct($_item->getProduct())->setImageId('cart_page_product_thumbnail')->create()->toHtml(); ?></span>
<?php } ?>

Note that: USED OF direct object Manager is not a good idea

Amit Bera
  • 77,456
  • 20
  • 123
  • 237
  • Thanks a lot!!! It really helps but I'm thinking that we don't need to separate if it's simple product. We can use 'sku' to get the image for both simple and configurable product type. – s.w Apr 08 '19 at 09:49
  • why directly using object manager is not a good idea? – s.w Apr 08 '19 at 09:56
  • See the article, https://magento.stackexchange.com/questions/117098/magento-2-to-use-or-not-to-use-the-objectmanager-directly – Amit Bera Apr 08 '19 at 10:13