1

In Magento 2 how to show an image in the custom column on the sales order grid. I added a custom dynamic column in sales order grid Magento 2

enter image description here

Vendor\Module\Ui\Component\Listing\DataProvider.php

<?php
namespace Vendor\Module\Ui\Component\Listing;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\ReportingInterface;
use Magento\Framework\Api\Search\SearchCriteria;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\App\RequestInterface;

class DataProvider extends \Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
{
    const IMAGE_HEIGHT = '25';
    const IMAGE_STYLE = 'display: block;';
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        ReportingInterface $reporting,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        RequestInterface $request,
        FilterBuilder $filterBuilder,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct($name, $primaryFieldName, $requestFieldName, $reporting, $searchCriteriaBuilder, $request, $filterBuilder, $meta, $data);
        $this->orderRepository = $orderRepository;
        $this->_storeManager = $storeManager;
    }   
    public function getData()
    {
        $height =  self::IMAGE_HEIGHT;
        $style =  self::IMAGE_STYLE;
        $data = parent::getData();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $collectionFlag = $objectManager->create('Vendor\Module\Model\ResourceModel\Orderflag\Collection');
        foreach ($data['items'] as &$item) {
        $collection = $objectManager->create('Vendor\Module\Model\ResourceModel\Ordercolumn\Collection')
        ->addFieldToSelect(array('column_id','column_name'));
            if($collection->getSize()){
                foreach( $collection  as $column){
                     foreach($collectionFlag  as $flagValue) {
                     $srcImage = $this->_storeManager->getStore()
                        ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) .$flagValue->getData('image_icon');
                    $image = sprintf("<img src='".$srcImage."' height='".$height."'>");    
                     if($column->getData('column_id') == $flagValue->getData('column_name')):
                      
                         $item[$column->getData('column_id')] =  $image;  
                            //echo $item[$column->getData('column_id')]; 
                    else:
                         $item[$column->getData('column_id')]=  'N/A';
                    endif;                   
                    }
                }
            }          
        }      
        return $data;
    }
}

sales_order_grid.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <dataSource name="sales_order_grid_data_source">
        <dataProvider class="Vendor\Module\Ui\Component\Listing\DataProvider" name="sales_order_grid_data_source" />
    </dataSource>
    <columns name="sales_order_columns" class="Vendor\Module\Ui\Component\Listing\Columns" />  
</listing>

Vendor\Module\Ui\Component\Listing\Columns.php

<?php

namespace Vendor\Module\Ui\Component\Listing;

use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Vendor\Module\Ui\Component\Listing\Column\CustomColumnCreator;

class Columns extends \Magento\Ui\Component\Listing\Columns
{
    /**
     * @var CustomColumnCreator
     */
    private $columnCreator;

    public function __construct(
        ContextInterface $context,
        CustomColumnCreator $columnCreator,
        array $components = [],
        array $data = []
    ) {
        parent::__construct($context, $components, $data);
        $this->columnCreator = $columnCreator;
    }

    public function prepare()
    {
        
            $billingNameColumn = $this->components['billing_name'];
            
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $collection = $objectManager->create('Vendor\Module\Model\ResourceModel\Ordercolumn\Collection')
            ->addFieldToSelect(array('column_id','column_name'));
             if($collection->getSize()){
                 foreach ( $collection  as $flag){
                  
                   $column = $this->columnCreator->addColumnFromExistingColumn(
                    $billingNameColumn,
                    $flag->getData('column_id'),
                    $flag->getData('column_name'),
                    11
                );
                $this->addComponent($flag->getData('column_id'), $column);
                 }
             }
        parent::prepare();
    }


}

I added a custom dynamic column in sales order grid Magento 2

Reference: Add custom dynamic column in sales order grid Magento 2

5
  • using ui component ?? Oct 23, 2020 at 13:15
  • Can you please refer my updated post Oct 23, 2020 at 13:36
  • Did you get solution? Oct 26, 2020 at 5:00
  • No, i didn't get any answer Oct 27, 2020 at 5:01
  • Make sure you have set placeholder image in configuration to display when you have no image. Oct 27, 2020 at 5:56

3 Answers 3

1
+50

In the class \Mbs\SalesGrid\Ui\Component\Listing\Column\CustomColumnCreator, you need to look for the function addColumnFromExistingColumn

then, change this function from

public function addColumnFromExistingColumn(
        \Magento\Framework\View\Element\UiComponentInterface $existingColumn,
        $columnName,
        $label,
        $sortOrder
    ) {
        $config = $existingColumn->getConfiguration();
        $config['label'] = $label;

        $arguments = [
            'data' => [
                'config' => $config,
                'sortOrder' => $sortOrder
            ],
            'context' => $existingColumn->getContext(),
        ];

        return $this->componentFactory->create($columnName, 'column', $arguments);
    }

to

 public function addColumnFromExistingColumn(
            \Magento\Framework\View\Element\UiComponentInterface $existingColumn,
            $columnName,
            $label,
            $sortOrder
        ) {
            $config = $existingColumn->getConfiguration();
            $config['label'] = $label;
            $config['bodyTmpl'] = 'ui/grid/cells/html';
    
            $arguments = [
                'data' => [
                    'config' => $config,
                    'sortOrder' => $sortOrder
                ],
                'context' => $existingColumn->getContext(),
            ];
    
            return $this->componentFactory->create($columnName, 'column', $arguments);
        }

If you use this function on several columns, do let me know and I can adjust something more subtil. Good luck

2
  • Thank you so much it's working @Herve Tribouilloy Oct 29, 2020 at 4:47
  • Amazing, thanks @divyasekar, good day to you Oct 29, 2020 at 6:08
1

Follow this below steps :

Create sales_order_grid.xml file at app/code/Vendor/Module/view/adminhtml/ui_component/ and add this below code :

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <columns name="sales_order_columns">       
        <column name="logo" class="Vendor\Module\Ui\Component\Logo">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
                    <item name="label" xsi:type="string" translate="true">Logo</item>
                    <item name="altField" xsi:type="string">title</item>
                    <item name="has_preview" xsi:type="string">1</item>
                    <item name="sortOrder" xsi:type="number">30</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Create Logo.php file at app/code/Vendor/Module/Ui/Component/ and add this below code :

<?php

declare (strict_types = 1);

namespace Vendor\Module\Ui\Component;

use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Listing\Columns\Column;

class Logo extends Column
{
    const ALT_FIELD = 'title';

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var \Magento\Catalog\Helper\Image
     */
    protected $imageHelper;

    /**
     * @param ContextInterface              $context
     * @param UiComponentFactory            $uiComponentFactory
     * @param StoreManagerInterface         $storeManager
     * @param \Magento\Catalog\Helper\Image $imageHelper
     * @param array                         $components
     * @param array                         $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        StoreManagerInterface $storeManager,
        \Magento\Catalog\Helper\Image $imageHelper,
        array $components = [],
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        $this->imageHelper = $imageHelper;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * @param array $dataSource
     *
     * @return array
     */
    public function prepareDataSource(array $dataSource): array
    {
        parent::prepareDataSource($dataSource);

        if (isset($dataSource['data']['items'])) {
            $fieldName = $this->getData('name');
            foreach ($dataSource['data']['items'] as &$item) {
                $url = '';
                if (isset($item[$fieldName])) {
                    if ($item[$fieldName] != '') {
                        $url = $this->storeManager->getStore()->getBaseUrl(
                            \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                        ) . "catalog/product/custom" . $item[$fieldName];
                    } else {
                        $url = $this->imageHelper->getDefaultPlaceholderUrl('small_image');
                    }
                } else {
                    $url = $this->imageHelper->getDefaultPlaceholderUrl('small_image');
                }
                $item[$fieldName . '_src'] = $url;
                $item[$fieldName . '_alt'] = $this->getAlt($item) ?: '';
                $item[$fieldName . '_orig_src'] = $url;
            }
        }

        return $dataSource;
    }

    protected function getAlt($row)
    {
        $altField = $this->getData('config/altField') ?: self::ALT_FIELD;
        return isset($row[$altField]) ? $row[$altField] : null;
    }
}

Here, I used code like that if your image will not available then, placeholder image will be display.

catalog/product/custom => you can add your image directory here.

Output :

enter image description here

Reference : Click Here

6
  • I don't have a static custom column in sales_order_grid like <column name="logo"> here my sales_order_grid.xml file prnt.sc/v7ma97 Oct 27, 2020 at 6:00
  • You can replace my xml code if you want to just add 1 single column. Oct 27, 2020 at 6:02
  • If you have dynamic columns then, could you please upload Columns.php file? Oct 27, 2020 at 6:05
  • I posted a Column.php file in my question. can you please refer the above-posted question Oct 27, 2020 at 6:10
  • Why you created Columns.php file? Could you please explain me? Oct 27, 2020 at 6:43
1

sales_order_grid.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <columns name="sales_order_columns">
        <column name="imagedata" class="Vendorename\ModuleName\Ui\Component\ImageData">
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                 <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
                 <item name="sortable" xsi:type="boolean">false</item>
                 <item name="altField" xsi:type="string">store image</item>
                 <item name="has_preview" xsi:type="string">1</item>
                  <item name="filter" xsi:type="string">text</item>
                  <item name="label" xsi:type="string" translate="true">Image</item>
                  <item name="sortOrder" xsi:type="number">80</item>
               </item>
           </argument>
        </column>
    </columns>
</listing>

app/code/Vendorename/Modulename/Ui/Component/

ImageData.php

<?php

declare (strict_types = 1);

namespace Vendorename\Modulename\Ui\Component;

use Magento\Ui\Component\Listing\Columns\Column;

class ImageData extends Column
{
    /**
     * @param array $dataSource
     *
     * @return array
     */
    public function prepareDataSource(array $dataSource): array
    {
        parent::prepareDataSource($dataSource);

        if (!isset($dataSource['data']['items'])) {
            return $dataSource;
        }
        foreach ($dataSource['data']['items'] as &$item) {
            $item[$this->getData('name') . '_src'] = "https://homepages.cae.wisc.edu/~ece533/images/watch.png";
            $item[$this->getData('name') . '_alt'] = "Image name";
            $item[$this->getData('name') . '_orig_src'] = "https://homepages.cae.wisc.edu/~ece533/images/watch.png";
        }

        return $dataSource;
    }
}

enter image description here

I Hope This Helps You.

17
  • Can you please refer the updated question Oct 23, 2020 at 13:33
  • Please check and update me.
    – Msquare
    Oct 23, 2020 at 13:37
  • I will check and update you Oct 24, 2020 at 4:40
  • I tried your code but it shows an error prnt.sc/v5rvz9 Oct 24, 2020 at 5:48
  • update in sales_order_grid.xml. please add filed img into sales_order table by UpgradeSchema.php
    – Msquare
    Oct 24, 2020 at 5:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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