Magento2 | PWA | GraphQL

How to Display Product Image in Frontend Order Detail Page of Magento 2


 


In this post we will see how to add product image in sales order view page in frontend in Magento2.

We will do it by creating custom module.

You can find complete module on Magelearn_Salesorder.

Create folder in app/code/Magelearn/Salesorder

Add registration.php file in it:
<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Magelearn_Salesorder', __DIR__
);
Add composer.json file in it:
{
    "name": "magelearn/module-salesorder",
    "description": "Magento2 Display Product images on Sales Order View page",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@mage2gen.com",
            "name": "Mage2Gen"
        },
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\Salesorder\\": ""
        }
    }
}
Add etc/module.xml file:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Magelearn_Salesorder" setup_version="1.0.0"/>
</config>
Now to add product image in magento frontend Sales Order view page, we will override Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer block with our custom block. 

We will Add code to get product image in that.
Add etc/di.xml file:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer"
                type="Magelearn\Salesorder\Block\Item\Renderer"/>
</config>
Add Block/Item/Renderer.php file:
<?php

namespace Magelearn\Salesorder\Block\Item;

use Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer as DefaultRenderer;

class Renderer extends DefaultRenderer
{
    /**
     * Magento string lib
     *
     * @var \Magento\Framework\Stdlib\StringUtils
     */
    protected $string;

    /**
     * @var \Magento\Catalog\Model\Product\OptionFactory
     */
    protected $_productOptionFactory;

    /**
     * @var \Magento\Catalog\Block\Product\ImageBuilder
     */
    protected $imageBuilder;
	
	protected $_productImageHelper;
	
	protected $_productRepository;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\Stdlib\StringUtils $string
     * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Stdlib\StringUtils $string,
        \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory,
        \Magento\Catalog\Block\Product\ImageBuilder $imageBuilder,
        \Magento\Catalog\Helper\Image $productImageHelper,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        array $data = []
    ) {
        $this->imageBuilder = $imageBuilder;
		$this->_productImageHelper = $productImageHelper;
		$this->_productRepository = $productRepository;
        parent::__construct($context, $string, $productOptionFactory, $data);
    }

    /**
     * Get item product
     *
     * @return \Magento\Catalog\Model\Product
     * @codeCoverageIgnore
     */
    public function getProduct()
    {
        return $this->getItem()->getProduct();
    }

    /**
     * Identify the product from which thumbnail should be taken.
     *
     * @return \Magento\Catalog\Model\Product
     * @codeCoverageIgnore
     */
    public function getProductForThumbnail()
    {
        return $this->getProduct();
    }

    /**
     * Retrieve product image
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param string $imageId
     * @param array $attributes
     * @return \Magento\Catalog\Block\Product\Image
     */
    public function getImage($product, $imageId, $attributes = [])
    {
        return $this->imageBuilder->setProduct($product)
            ->setImageId($imageId)
            ->setAttributes($attributes)
            ->create();
    }
	/**
     * Schedule resize of the image
     * $width *or* $height can be null - in this case, lacking dimension will be calculated.
     *
     * @see \Magento\Catalog\Model\Product\Image
     * @param int $width
     * @param int $height
     * @return $this
     */
    public function resizeImage($product, $imageId, $width, $height = null)
    {
        $resizedImage = $this->_productImageHelper
                           ->init($product, $imageId)
                           ->constrainOnly(TRUE)
                           ->keepAspectRatio(TRUE)
                           ->keepTransparency(TRUE)
                           ->keepFrame(FALSE)
                           ->resize($width, $height);
        return $resizedImage;
    }
	
	public function getProductById($id)
    {
        return $this->_productRepository->getById($id);
    }
    
    public function getProductBySku($sku)
    {
        return $this->_productRepository->get($sku);
    }
}
1. constrainOnly(): This will not resize an image that is smaller than the dimensions inside the resize() part. The default value is true in Magento 2.

2. keepTransparency(): By default, it is True, which means the image will not lose transparency.

3. keepFrame(): Choose (True) will remove the background and set the image to desired width/height and choose (false) will doesn’t remove.

4: keepAspectRatio(true): It the aspect ratio of the frame, for example, if the frame is 360: 240, the aspect ratio is 3: 2, if there is a change, it will not change the aspect ratio when resizing graphics, keepAspectRadio (false) It will doesn’t maintain the ratio.

Now we will add different layout files to override the defualt phtml file for order item, order invoice and order shipment.

Add app/code/Magelearn/Salesorder/view/frontend/layout/sales_order_item_renderers.xml file.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="sales.order.items.renderers">
            <block class="Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer" name="sales.order.items.renderers.default" as="default" template="Magelearn_Salesorder::order/items/renderer/default.phtml"/>
        </referenceBlock>
    </body>
</page>

Add app/code/Magelearn/Salesorder/view/frontend/layout/sales_order_invoice_renderers.xml file.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="sales.order.invoice.renderers">
            <block class="Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer" name="sales.order.invoice.renderers.default" as="default" template="Magelearn_Salesorder::order/invoice/items/renderer/default.phtml"/>
        </referenceBlock>
    </body>
</page>

Add app/code/Magelearn/Salesorder/view/frontend/layout/sales_order_shipment_renderers.xml file.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="sales.order.shipment.renderers">
            <block class="Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer" name="sales.order.shipment.renderers.default" as="default" template="Magelearn_Salesorder::order/shipment/items/renderer/default.phtml"/>
        </referenceBlock>
    </body>
</page>
Now we will add our custom module's phtml file and add product images code in it.

copy file form vendor/magento/module-sales/view/frontend/templates/order/items/renderer/default.phtml, vendor/magento/module-sales/view/frontend/templates/order/invoice/items/renderer/default.phtml and vendor/magento/module-sales/view/frontend/templates/order/shipment/items/renderer/default.phtml and add it into our custom module template file.

Add app/code/Magelearn/Salesorder/view/frontend/templates/order/items/renderer/default.phtml file:
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var  $block \Magelearn\Salesorder\Block\Item\Renderer */
$_item = $block->getItem();
?>
<tr id="magelearn order-item-row-<?= (int) $_item->getId() ?>">
    <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>">
        <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong>
        <?php if ($_options = $block->getItemOptions()) : ?>
            <dl class="item-options">
            <?php foreach ($_options as $_option) : ?>
                <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                <?php if (!$block->getPrintStatus()) : ?>
                    <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?>
                    <dd<?= (isset($_formatedOptionValue['full_view']) ? ' class="tooltip wrapper"' : '') ?>>
                        <?= $block->escapeHtml($_formatedOptionValue['value'], ['a', 'img']) ?>
                        <?php if (isset($_formatedOptionValue['full_view'])) : ?>
                            <div class="tooltip content">
                                <dl class="item options">
                                    <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                                    <dd><?= $block->escapeHtml($_formatedOptionValue['full_view']) ?></dd>
                                </dl>
                            </div>
                        <?php endif; ?>
                    </dd>
                <?php else : ?>
                    <dd><?= $block->escapeHtml((isset($_option['print_value']) ? $_option['print_value'] : $_option['value'])) ?></dd>
                <?php endif; ?>
            <?php endforeach; ?>
            </dl>
        <?php endif; ?>
        <?php $addtInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
        <?php if ($addtInfoBlock) : ?>
            <?= $addtInfoBlock->setItem($_item)->toHtml() ?>
        <?php endif; ?>
        <?= $block->escapeHtml($_item->getDescription()) ?>
        <?php
        $imageId = 'product_base_image';
		$width = 200;
		$height = 300;
		$sku = $_item->getSku();
		$_product = $block->getProductBySku($sku);
		$resizedImageUrl = $block->resizeImage($_product, 'product_base_image', $width, $height)->getUrl();
        ?>
        <img src="<?php echo $resizedImageUrl;?>" alt="" />
        
		
    </td>
    <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td>
    <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>">
        
        <?php /* @escapeNotVerified */ echo $block->getProductPrice($_product) ?>
    </td>
    <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty')) ?>">
        <ul class="items-qty">
        <?php if ($block->getItem()->getQtyOrdered() > 0) : ?>
            <li class="item">
                <span class="title"><?= $block->escapeHtml(__('Ordered')) ?></span>
                <span class="content"><?= (float) $block->getItem()->getQtyOrdered() ?></span>
            </li>
        <?php endif; ?>
        <?php if ($block->getItem()->getQtyShipped() > 0) : ?>
            <li class="item">
                <span class="title"><?= $block->escapeHtml(__('Shipped')) ?></span>
                <span class="content"><?= (float) $block->getItem()->getQtyShipped() ?></span>
            </li>
        <?php endif; ?>
        <?php if ($block->getItem()->getQtyCanceled() > 0) : ?>
            <li class="item">
                <span class="title"><?= $block->escapeHtml(__('Canceled')) ?></span>
                <span class="content"><?= (float) $block->getItem()->getQtyCanceled() ?></span>
            </li>
        <?php endif; ?>
        <?php if ($block->getItem()->getQtyRefunded() > 0) : ?>
            <li class="item">
                <span class="title"><?= $block->escapeHtml(__('Refunded')) ?></span>
                <span class="content"><?= (float) $block->getItem()->getQtyRefunded() ?></span>
            </li>
        <?php endif; ?>
        </ul>
    </td>
    <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>">
        <?= $block->getItemRowTotalHtml() ?>
    </td>
</tr>
Add app/code/Magelearn/Salesorder/view/frontend/templates/order/invoice/items/renderer/default.phtml file:
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<?php /** @var  $block \Magelearn\Salesorder\Block\Item\Renderer */ ?>
<?php $_item = $block->getItem() ?>
<?php $_order = $block->getItem()->getOrderItem()->getOrder() ?>
<tr id="order-item-row-<?= (int) $_item->getId() ?>">
    <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>">
        <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong>
        <?php if ($_options = $block->getItemOptions()): ?>
            <dl class="item-options">
            <?php foreach ($_options as $_option): ?>
                <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                <?php if (!$block->getPrintStatus()): ?>
                    <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?>
                    <dd<?= (isset($_formatedOptionValue['full_view']) ? ' class="tooltip wrapper"' : '') ?>>
                        <?= $block->escapeHtml($_formatedOptionValue['value'], ['a']) ?>
                        <?php if (isset($_formatedOptionValue['full_view'])): ?>
                            <div class="tooltip content">
                                <dl class="item options">
                                    <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                                    <dd><?= $block->escapeHtml($_formatedOptionValue['full_view']) ?></dd>
                                </dl>
                            </div>
                        <?php endif; ?>
                    </dd>
                <?php else: ?>
                    <dd><?= $block->escapeHtml($_option['print_value'] ?? $_option['value']) ?></dd>
                <?php endif; ?>
            <?php endforeach; ?>
            </dl>
        <?php endif; ?>
        <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
        <?php if ($addInfoBlock): ?>
            <?= $addInfoBlock->setItem($_item->getOrderItem())->toHtml() ?>
        <?php endif; ?>
        <?= $block->escapeHtml($_item->getDescription()) ?>
        <?php
        $imageId = 'product_base_image';
		$width = 200;
		$height = 300;
		$sku = $_item->getSku();
		$_product = $block->getProductBySku($sku);
		$resizedImageUrl = $block->resizeImage($_product, 'product_base_image', $width, $height)->getUrl();
        ?>
        <img src="<?php echo $resizedImageUrl;?>" alt="" />
    </td>
    <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>">
        <?= /* @noEscape */ $block->prepareSku($block->getSku()) ?>
    </td>
    <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>">
        <?= $block->getItemPriceHtml() ?>
    </td>
    <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Invoiced')) ?>">
        <span class="qty summary"><?= (float) $_item->getQty() ?></span>
    </td>
    <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>">
        <?= $block->getItemRowTotalHtml() ?>
    </td>
</tr>
Add app/code/Magelearn/Salesorder/view/frontend/templates/order/shipment/items/renderer/default.phtml file:

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<?php $_item = $block->getItem() ?>
<?php $_order = $block->getItem()->getOrderItem()->getOrder() ?>
<tr id="order-item-row-<?= (int) $_item->getId() ?>">
    <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>">
        <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong>
        <?php if ($_options = $block->getItemOptions()): ?>
            <dl class="item options">
            <?php foreach ($_options as $_option): ?>
                <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                <?php if (!$block->getPrintStatus()): ?>
                    <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?>
                    <dd<?= (isset($_formatedOptionValue['full_view']) ? ' class="tooltip wrapper"' : '') ?>>
                        <?= $block->escapeHtml($_formatedOptionValue['value'], ['a']) ?>
                        <?php if (isset($_formatedOptionValue['full_view'])): ?>
                        <div class="tooltip content">
                            <dl class="item options">
                                <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                                <dd><?= $block->escapeHtml($_formatedOptionValue['full_view']) ?></dd>
                            </dl>
                        </div>
                        <?php endif; ?>
                    </dd>
                <?php else: ?>
                    <?php $optionValue = isset($_option['print_value']) ? $_option['print_value'] : $_option['value'] ?>
                    <dd><?= $block->escapeHtml($optionValue) ?></dd>
                <?php endif; ?>
            <?php endforeach; ?>
            </dl>
        <?php endif; ?>
        <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
        <?php if ($addInfoBlock): ?>
            <?= $addInfoBlock->setItem($_item->getOrderItem())->toHtml() ?>
        <?php endif; ?>
        <?= $block->escapeHtml($_item->getDescription()) ?>
        <?php
        $imageId = 'product_base_image';
		$width = 200;
		$height = 300;
		$sku = $_item->getSku();
		$_product = $block->getProductBySku($sku);
		$resizedImageUrl = $block->resizeImage($_product, 'product_base_image', $width, $height)->getUrl();
        ?>
        <img src="<?php echo $resizedImageUrl;?>" alt="" />
    </td>
    <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>">
        <?= /* @noEscape */ $block->prepareSku($block->getSku()) ?>
    </td>
    <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Shipped')) ?>"><?= (float) $_item->getQty() ?></td>
</tr>
0 Comments On "How to Display Product Image in Frontend Order Detail Page of Magento 2"

Back To Top