Magento 2: How to Add a New Column in Admin Grid

Adding a new column in Magento 2 admin grid is not a complex task. In this blog, we will see how to add a new column to the Magento 2 admin sales order grid very easily.

Step 1: Module Registration

Create a new custom module based on the Magento 2 structure in the below file path,

File Path: app/code/BlogTreat/CustomGrid/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'BlogTreat_CustomGrid',
    __DIR__
);

Step 2: Module Configuration

Create a module.xml file in the below file path to define new Magento 2 extension

File Path: app/code/BlogTreat/CustomGrid/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="BlogTreat_CustomGrid" setup_version="1.0.0">
    	<sequence>
            <module name="Magento_Sales"/>
    	</sequence>
    </module>
</config>

Step 3: Configure UI Grid Component to Display Custom Column

To reflect the custom column on admin panel sales order grid, we have to extend sales_order_grid UI component by adding a UI configuration file in our custom module.

File Path: app/code/BlogTreat/CustomGrid/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="total_paid" class="BlogTreat\CustomGrid\Ui\Component\Listing\Column\PurchasedPrice">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">textRange</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="label" xsi:type="string" translate="true">Total Paid</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

In the above code, we are rendering the custom class BlogTreat\CustomGrid\Ui\Component\Listing\Column\PurchasedPrice which is used to display the value in the price format.

Create a PurchasedPrice.php file in the below file path and add the following code,

File Path: app/code/BlogTreat/CustomGrid/Ui/Component/Listing/Column/PurchasedPrice.php

<?php
namespace BlogTreat\CustomGrid\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\Framework\Pricing\PriceCurrencyInterface;

/**
 * Class Price
 */
class PurchasedPrice extends Column
{
    /**
     * @var PriceCurrencyInterface
     */
    protected $priceFormatter;

    /**
     * Constructor
     *
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param PriceCurrencyInterface $priceFormatter
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        PriceCurrencyInterface $priceFormatter,
        array $components = [],
        array $data = []
    ) {
        $this->priceFormatter = $priceFormatter;
        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) {
                $currencyCode = isset($item['order_currency_code']) ? $item['order_currency_code'] : null;
                $item[$this->getData('name')] =
                    $this->priceFormatter->format(
                        $item[$this->getData('name')],
                        false,
                        null,
                        null,
                        $currencyCode
                    );
            }
        }

        return $dataSource;
    }
}

After completing the above steps run the below SSH command in your Magento 2 root directory to install this custom module,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check whether the extension has been successfully installed in Magento 2 admin.

Once the extension has been installed you will be able to view the custom field in admin sales order grid as shown in the screenshot below,

Magento 2: How to Add a New Column in Admin Grid

Hope this helps.

Leave a Reply

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