Magento 2 – Add Product Details Column in Sales Order Grid

custom-column-gridmagento2sales-order-grid

I need to extra column to Sales Order Grid that displays product name or product SKU.

Best Answer

Create sales_order_grid.xml at

app/code/Vendor/Module/view/adminhtml/ui_component/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="products" class="Vendor\Module\Ui\Component\Listing\Column\Products">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="label" xsi:type="string" translate="true">Products</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Create Products.php at

app/code/Vendor/Module/Ui/Component/Listing/Column/Products.php

<?php

namespace Test\Test\Ui\Component\Listing\Column;

use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Framework\View\Element\UiComponent\ContextInterface;
use \Magento\Framework\View\Element\UiComponentFactory;
use \Magento\Ui\Component\Listing\Columns\Column;
use \Magento\Framework\Api\SearchCriteriaBuilder;

class Products extends Column
{
    protected $_orderRepository;
    protected $_searchCriteria;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $criteria,
        array $components = [],
        array $data = [])
    {
        $this->_orderRepository = $orderRepository;
        $this->_searchCriteria  = $criteria;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$items) {
                $productArr = [];
                $order  = $this->_orderRepository->get($items["entity_id"]);

                foreach ($order->getAllVisibleItems() as $item) {
                    $productArr[] = $item->getSku();
                    //$productArr[] = $item->getName(); //Get product name
                }
                $items['products'] = implode(' - ', $productArr);
                unset($productArr);
            }
        }
        return $dataSource;
    }
}

Now remove var/ and your output will look like:

OUTPUT:

enter image description here

Related Topic