Bhaveshpp

Professional Magento Developr - Healp eachother to grow

Magento2: How to add new column in seals order grid

27 May 2021 » magento2

add file Bhaveshpp/Custom/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="transaction" class="Bhaveshpp\Custom\UiComponent\Sales\Order\Listing\Column\Transaction">
            <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">Transaction</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Add ui component Bhaveshpp\Custom\UiComponent\Sales\Order\Listing\Column\Transaction

<?php

namespace Bhaveshpp\Custom\UiComponent\Sales\Order\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 Transaction 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 &$item) {
                $order  = $this->_orderRepository->get($item["entity_id"]);
                $total = $order->getGrandTotal();
                $item['transaction'] = $total;
            }
        }
        return $dataSource;
    }

}