Magento 2: How to Display Product Image on Admin Order Create Page

Magento 2 How to Display Product Image on Admin Order Create Page

Hello Magento Friends,

In this blog post, we’ll explore how to enhance the user experience by displaying product images directly on the admin order creation page.

When processing orders in the Magento 2 admin panel, administrators often need to refer to product details to ensure accurate fulfillment. While Magento 2 provides various product attributes and information on the order creation page, the absence of product images can make it challenging to quickly identify the products being ordered. By incorporating product images directly into the order creation interface, administrators can expedite order processing, reduce errors, and improve overall efficiency.

Steps to Display Product Image on Admin Order Create Page in Magento 2:

Step 1: First, we must create a “di.xml” file inside the etc folder using the code below

app\code\Vendor\Extension\etc\

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="\Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid" type="Vendor\Extension\Block\Adminhtml\OverrideOrder\Create\Search\Grid" />
</config>

Step 2: After that, create the “Grid.php” file inside the Search folder.

app\code\Vendor\Extension\Block\Adminhtml\OverrideOrder\Create\Search\

And add the below-mentioned code

<?php
namespace app\code\Vendor\Extension\Block\Adminhtml\OverrideOrder\Create\Search;

use Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\DataProvider\ProductCollection;
use Magento\Framework\App\ObjectManager;

/**
 * Adminhtml sales order create search products block
 *
 * @api
 * @author      Magento Core Team <core@magentocommerce.com>
 * @since 100.0.2
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
    /**
     * Sales config
     *
     * @var \Magento\Sales\Model\Config
     */
    protected $_salesConfig;

    /**
     * Session quote
     *
     * @var \Magento\Backend\Model\Session\Quote
     */
    protected $_sessionQuote;

    /**
     * Catalog config
     *
     * @var \Magento\Catalog\Model\Config
     */
    protected $_catalogConfig;

    /**
     * Product factory
     *
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productFactory;

    /**
     * @var ProductCollection $productCollectionProvider
     */
    private $productCollectionProvider;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Catalog\Model\Config $catalogConfig
     * @param \Magento\Backend\Model\Session\Quote $sessionQuote
     * @param \Magento\Sales\Model\Config $salesConfig
     * @param array $data
     * @param ProductCollection|null $productCollectionProvider
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\Config $catalogConfig,
        \Magento\Backend\Model\Session\Quote $sessionQuote,
        \Magento\Sales\Model\Config $salesConfig,
        array $data = [],
        ProductCollection $productCollectionProvider = null
    ) {
        $this->_productFactory = $productFactory;
        $this->_catalogConfig = $catalogConfig;
        $this->_sessionQuote = $sessionQuote;
        $this->_salesConfig = $salesConfig;
        $this->productCollectionProvider = $productCollectionProvider
            ?: ObjectManager::getInstance()->get(ProductCollection::class);
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * Constructor
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('sales_order_create_search_grid');
        $this->setRowClickCallback('order.productGridRowClick.bind(order)');
        $this->setCheckboxCheckCallback('order.productGridCheckboxCheck.bind(order)');
        $this->setRowInitCallback('order.productGridRowInit.bind(order)');
        $this->setDefaultSort('entity_id');
        $this->setFilterKeyPressCallback('order.productGridFilterKeyPress');
        $this->setUseAjax(true);
        if ($this->getRequest()->getParam('collapse')) {
            $this->setIsCollapsed(true);
        }
    }

    /**
     * Retrieve quote store object
     *
     * @return \Magento\Store\Model\Store
     */
    public function getStore()
    {
        return $this->_sessionQuote->getStore();
    }

    /**
     * Retrieve quote object
     *
     * @return \Magento\Quote\Model\Quote
     */
    public function getQuote()
    {
        return $this->_sessionQuote->getQuote();
    }

    /**
     * Add column filter to collection
     *
     * @param \Magento\Backend\Block\Widget\Grid\Column $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {
        // Set custom filter for in product flag
        if ($column->getId() == 'in_products') {
            $productIds = $this->_getSelectedProducts();
            if (empty($productIds)) {
                $productIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('entity_id', ['in' => $productIds]);
            } else {
                if ($productIds) {
                    $this->getCollection()->addFieldToFilter('entity_id', ['nin' => $productIds]);
                }
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }
        return $this;
    }

    /**
     * Prepare collection to be displayed in the grid
     *
     * @return $this
     */
    protected function _prepareCollection()
    {

        $attributes = $this->_catalogConfig->getProductAttributes();
        $store = $this->getStore();

        /* @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
        $collection = $this->productCollectionProvider->getCollectionForStore($store);
        $collection->addAttributeToSelect(
            $attributes
        );
        $collection->addAttributeToFilter(
            'type_id',
            $this->_salesConfig->getAvailableProductTypes()
        );

        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
     * Prepare columns
     *
     * @return $this
     */
    protected function _prepareColumns()
    {
         $this->addColumn(
            'thumbnail',
            [
                'filter' => false,
                'sortable' => false,
                'header' => __('Images'),
                'name' => 'thumbnail',
                'inline_css' => 'thumbnail',
                'index' => 'image',
                'class' => 'image',
                'renderer' => 'Vendor\Extension\Block\Adminhtml\Product\Grid\Renderer\Image',
            ]
        );
        $this->addColumn(
            'entity_id',
            [
                'header' => __('ID'),
                'sortable' => true,
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
                'index' => 'entity_id'
            ]
        );
        $this->addColumn(
            'name',
            [
                'header' => __('Product'),
                'renderer' => \Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\Renderer\Product::class,
                'index' => 'name'
            ]
        );
        $this->addColumn('sku', ['header' => __('SKU'), 'index' => 'sku']);
        $this->addColumn(
            'price',
            [
                'header' => __('Price'),
                'column_css_class' => 'price',
                'type' => 'currency',
                'currency_code' => $this->getStore()->getCurrentCurrencyCode(),
                'rate' => $this->getStore()->getBaseCurrency()->getRate($this->getStore()->getCurrentCurrencyCode()),
                'index' => 'price',
                'renderer' => \Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\Renderer\Price::class
            ]
        );

        $this->addColumn(
            'in_products',
            [
                'header' => __('Select'),
                'type' => 'checkbox',
                'name' => 'in_products',
                'values' => $this->_getSelectedProducts(),
                'index' => 'entity_id',
                'sortable' => false,
                'header_css_class' => 'col-select',
                'column_css_class' => 'col-select'
            ]
        );

        $this->addColumn(
            'qty',
            [
                'filter' => false,
                'sortable' => false,
                'header' => __('Quantity'),
                'renderer' => \Magento\Sales\Block\Adminhtml\Order\Create\Search\Grid\Renderer\Qty::class,
                'name' => 'qty',
                'inline_css' => 'qty',
                'type' => 'input',
                'validate_class' => 'validate-number',
                'index' => 'qty'
            ]
        );

        return parent::_prepareColumns();
    }

    /**
     * Get grid url
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl(
            'sales/*/loadBlock',
            ['block' => 'search_grid', '_current' => true, 'collapse' => null]
        );
    }

    /**
     * Get selected products
     *
     * @return mixed
     */
    protected function _getSelectedProducts()
    {
        $products = $this->getRequest()->getPost('products', []);

        return $products;
    }

    /**
     * Add custom options to product collection
     *
     * @return $this
     */
    protected function _afterLoadCollection()
    {
        $this->getCollection()->addOptionsToResult();
        return parent::_afterLoadCollection();
    }
}

Step 3: After that, create “Image.php” file inside Renderer folder.

app\code\Vendor\Extension\Block\Adminhtml\Product\Grid\Renderer\

And add the following code

<?php
namespace Vendor\Extension\Block\Adminhtml\Product\Grid\Renderer;

use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer;
use Magento\Framework\DataObject;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\View\Asset\Repository;
use Magento\Catalog\Helper\ImageFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Store\Model\StoreManager;
use Magento\Store\Model\ScopeInterface;

class Image extends AbstractRenderer
{
    private $_storeManager;
    private $helperImageFactory;
    private $assetRepos;
    private $adapterFactory;
    private $scopeConfig;
    private $storeManager;
    /**
     * @param \Magento\Backend\Block\Context $context
     * @param array $data
     */
    public function __construct(\Magento\Backend\Block\Context $context,
                                Repository $assetRepos,
                                ImageFactory $helperImageFactory,
                                AdapterFactory $adapterFactory,
                                StoreManager $storeManager,
                                StoreManagerInterface $storemanager, array $data = [])
    {
        $this->_storeManager = $storemanager;
        $this->assetRepos = $assetRepos;
        $this->helperImageFactory = $helperImageFactory;
        $this->adapterFactory = $adapterFactory;
        $this->storeManager = $storeManager;
        $this->scopeConfig = $context->getScopeConfig();

        parent::__construct($context, $data);
        $this->_authorization = $context->getAuthorization();
    }
    /**
     * Renders grid column
     *
     * @param Object $row
     * @return  string
     */
    public function render(DataObject $row)
    {
        $mediaDirectory = $this->_storeManager->getStore()->getBaseUrl(
            \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
        );

        if($this->_getValue($row)){
            $imageUrl = $mediaDirectory.'/catalog/product'.$this->_getValue($row);
        }else{
            $plUrl = $this->scopeConfig->getValue('catalog/placeholder/thumbnail_placeholder',ScopeInterface::SCOPE_STORE,0);
            $imageUrl = $mediaDirectory.'/catalog/product/placeholder/'.$plUrl;
        }
        return '<img src="'.$imageUrl.'" style="width: 5rem;border: 1px solid #d6d6d6;"/>';

    }
}

Output:

Magento 2: Display Product Image on Admin Order Create Page

Conclusion:

By incorporating product images into the Magento 2 admin order creation page, you can streamline order processing and improve user experience for administrators. This enhancement enables quicker identification of products, reduces errors, and enhances overall efficiency in managing orders. With the straightforward implementation outlined in this guide, you can easily enhance your Magento 2 admin panel to meet the needs of your e-commerce business.

Related Article – 

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

If you have doubts, let me know through the comment box. Share the tutorial with your friends and stay updated with us for more such Magento 2 solutions.

Happy Coding!

Previous Article

Google March 2024 Core Update

Next Article

Google's New Move: Eliminating AI-Generated SEO Content for Better Organic Search Results

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨