1

I have been able to add custom attribute to the orders grid but do not know how to render sold product thumbbnail. How to show product picture on the Sales -> Orders grid?

So when a product is sold it would be great to see its picture next to the product SKU in the Sales -> Orders grid. So when my friend helps me to pack all the orders, he can see how the product looks like and he can easily identify it.

Any Idea?

0

Try this article, maybe it works https://magecomp.com/blog/display-product-image-backend-order-detail-page-magento-2/

First, we need to create custom column and call our code to display product image. app\code\Vendor\Extension\view\adminhtml\layout\sales_order_view.xml

Now we need to create default.phtml file which contains our logic of showcasing product image. app\code\Vendor\Extension\view\adminhtml\templates\order\view\items\renderer\default.phtml

Click the link of the article to see the code.

  • Be aware that one reader has reported a bug with the code in this article - that If the admin deletes a product then the order can't open. – Freshwebs Oct 28 at 10:29
0

I have done the same, So share my code hope it helps

First, create a sample module and follow below instruction. Consider here Packagename of the module is Stackoverflow_Answer

Add below dependency in etc/module.xml

<?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="Stackoverflow_Answer" setup_version="0.0.2">
         <sequence>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

Create a vendor/Module/view/adminhtml/layout/sales_order_view.xml and put below code

<?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="order_items">
            <arguments>
                <argument name="columns" xsi:type="array">

                    <item name="image" xsi:type="string" translate="true">Product Image</item>
                    <item name="product" xsi:type="string" translate="true">Product</item>
                    <item name="status" xsi:type="string" translate="true">Item Status</item>
                    <item name="price-original" xsi:type="string" translate="true">Original Price</item>
                    <item name="price" xsi:type="string" translate="true">Price</item>
                    <item name="ordered-qty" xsi:type="string" translate="true">Qty</item>
                    <item name="subtotal" xsi:type="string" translate="true">Subtotal</item>
                    <item name="tax-amount" xsi:type="string" translate="true">Tax Amount</item>
                    <item name="tax-percent" xsi:type="string" translate="true">Tax Percent</item>
                    <item name="discont" xsi:type="string" translate="true">Discount Amount</item>
                    <item name="total" xsi:type="string" translate="true">Row Total</item>
                </argument>
            </arguments> 
            <referenceBlock name="default_order_items_renderer">
                <arguments>
                    <argument name="columns" xsi:type="array">

                        <item name="image" xsi:type="string" translate="false">col-image</item>
                        <item name="product" xsi:type="string" translate="false">col-product</item>
                        <item name="status" xsi:type="string" translate="false">col-status</item>
                        <item name="price-original" xsi:type="string" translate="false">col-price-original</item>
                        <item name="price" xsi:type="string" translate="false">col-price</item>
                        <item name="qty" xsi:type="string" translate="false">col-ordered-qty</item>
                        <item name="subtotal" xsi:type="string" translate="false">col-subtotal</item>
                        <item name="tax-amount" xsi:type="string" translate="false">col-tax-amount</item>
                        <item name="tax-percent" xsi:type="string" translate="false">col-tax-percent</item>
                        <item name="discont" xsi:type="string" translate="false">col-discont</item>
                        <item name="total" xsi:type="string" translate="false">col-total</item>
                    </argument>
                </arguments>
            </referenceBlock>
        </referenceBlock>
    </body>
</page>

Create etc/di.xml and add below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer">
        <plugin name="order-view-image" type="Stackoverflow\Answer\Plugin\DefaultRendererPlugin" sortOrder="1" />
    </type>
</config>

Create Plugin/DefaultRendererPlugin.php and add below code

<?php
namespace Stackoverflow\Answer\Plugin;

use \Magento\Catalog\Helper\Image as ImageHelper;

class DefaultRendererPlugin {

    /**
     * @var \Magento\Catalog\Helper\Image $imageHelper
    */
    protected $imageHelper;

    /**
     * @param ImageHelper      $imageHelper
     */
    public function __construct
    (
        ImageHelper $imageHelper
    )
    {
        $this->imageHelper      = $imageHelper;
    }

    public function aroundGetColumnHtml(\Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer $defaultRenderer, \Closure $proceed,\Magento\Framework\DataObject $item, $column, $field=null) {

                if($column === 'image') {
            $img = $this->imageHelper->init($item->getProduct(), 'small_image')->setImageFile($item->getProduct()->getImage())->resize(200)->getUrl();
            $result = '<img src="'.$img.'" alt="'.$item->getName().'" />';
        }
        else {
            if($field) {
                $result = $proceed($item,$column,$field);
            }
            else {
                $result = $proceed($item,$column);
            }
        }

        return $result;
    }
} 

It will display same result as mentioned in below link screencast.com/t/KlpfPod4

This is for order grid as we discussed

Create sales_order_grid.xml under "SR\MagentoCommunity\view\adminhtml\ui_component" and put or append below code.

<column name="product_skus_for_image" class="SR\MagentoCommunity\Ui\Component\Listing\Column\Productimage">
                    <argument name="data" xsi:type="array">
                        <item name="js_config" xsi:type="array">
                            <item name="Component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
                        </item>
                        <item name="config" xsi:type="array">
                            <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
                            <item name="filter" xsi:type="string">text</item>
                            <item name="visible" xsi:type="boolean">true</item>
                            <item name="label" xsi:type="string" translate="true">product Image</item>
                        </item>
   </argument>
</column>

Next step. create Productimage.php under "SR\MagentoCommunity\Ui\Component\Listing\Column\" and put below code.

<?php
namespace SR\MagentoCommunity\Ui\Component\Listing\Column;

use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Catalog\Model\ProductRepository;
use Magento\Catalog\Helper\Image;

class Productimage extends Column
{
    /**
     * @var ProductRepository
     */
    private $productRepository;

    /**
     * ItemLocation constructor.
     *
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param ProductRepository $productRepository
     * @param array $components
     * @param array $data
     */

    protected $_imageHelper;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        ProductRepository $productRepository,
        Image $imageHelper,
        array $components = [],
        array $data = []
    ) {
        $this->productRepository = $productRepository;
         $this->_imageHelper = $imageHelper;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {

          foreach($dataSource['data']['items'] as & $item) {
                if($item) {
                    if($item['product_skus_for_image']) {
                       $allSkus =  explode("|",$item['product_skus_for_image']);
                       $allProductImage = '';
                       foreach($allSkus as $sku)
                       { 
                         $product = $this->productRepository->get($sku);
                         if($product) { 
                              $img = $this->_imageHelper->init($product, 'small_image')->setImageFile($product->getImage())->resize(200)->getUrl();
                           $allProductImage .='<img src="'.$img.'" alt="'.$product->getName().'" />';
                           }
                       }
                       $item['product_skus_for_image'] = $allProductImage;
                    }

                }
            }

        }

        return $dataSource;
    }
}

create di.xml under SR/MagentoCommunity/etc and add below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <plugin name="join_sales_order_grid_with_product"
                type="SR\MagentoCommunity\Plugin\UiComponent\DataProvider\CollectionFactory" sortOrder="1" />
    </type>

</config>

Create CollectionFactory.php (plugin file) at SR\MagentoCommunity\Plugin\UiComponent\DataProvider and paste below code.

    <?php
namespace SR\MagentoCommunity\Plugin\UiComponent\DataProvider;

use Magento\Sales\Model\ResourceModel\Order\Grid\Collection as OrderGridCollection;

class CollectionFactory
{
    public function afterGetReport(
        \Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject,
        $collection,
        $requestName
    ) {
        if ($requestName == 'sales_order_grid_data_source') {
            if ($collection instanceof OrderGridCollection) {
                $collection->getSelect()
                    ->join(
                        $collection->getTable('sales_order_item'),
                        'main_table.entity_id = '.$collection->getTable('sales_order_item').'.order_id',
                        [
                                                          'product_skus_for_image' => new \Zend_Db_Expr('GROUP_CONCAT(`sales_order_item`.sku SEPARATOR "|")'),
                        ]
                    )

                    ->join(
                            $collection->getTable('sales_order'),
                            'main_table.entity_id = '.$collection->getTable('sales_order').'.entity_id',
                            [
                            'product_shipping' => new \Zend_Db_Expr('GROUP_CONCAT(`sales_order`.shipping_description SEPARATOR "|")'),

                            ]
                    )


                    ->where('parent_item_id IS NULL')
                    ->group('main_table.entity_id');
            }
        }

        return $collection;
    }
}

Run setup:upgrade and flush cache. Hope it helps.

  • Well, I have tried to create module you have posted here, but its seems this is not working, it is not even change the sales order grid ( something must missing from the code) I have also tried to implement it into my own existing custom sales order grid without any luck. I believe that the PHP part of your module is what I looking for. I just can't render the image into the grid. – Peter May 28 at 11:44
  • @peter, Check my updated answer. – Amitkumar solanki Jun 1 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.