Magento 2 : How to add a column in Order Grid and Order

Posted Over 3 years ago. Visible to the public.

Following steps explain how to add new column in order and grid tables

1) Add the columns in order, quote and grid tables using declarative schema

2) Add arguments to Magento\Sales\Model\ResourceModel\Order\Grid virtual class that already defined in Magento_Sales di.xml

<virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="channel" xsi:type="string">sales_order.channel</item>
            </argument>
        </arguments>
    </virtualType>

3) Create event.xml and Observer class to save the data to quote and order

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_model_service_quote_submit_before">
        <observer name="CheckoutSubmitQuote" instance="Vasan\Order\Observer\SubmitQuote" />
    </event>
</config>
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;

class SubmitQuote implements ObserverInterface
{
    protected $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function execute(Observer $observer)
    {
        $this->logger->info('Observer executed for order creation');
        $quote = $observer->getData('quote');
        $order = $observer->getData('order');

        $channel = $quote->getData('channel');
        $this->logger->info('The value of channel before save :' . $channel);

        if ($channel) {
            $order->setData('channel', $channel);
        }
    }
}

4) Add the column in sales_order_grid.xml in ui_component

<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="channel">
            <settings>
                <filter>text</filter>
                <label translate="true">Channel</label>
            </settings>
        </column>
    </columns>
</listing>
vasan
Last edit
Over 2 years ago
vasan
Keywords
Order, Grid, Order, attribute
Posted by vasan to vasan's deck (2020-12-25 18:04)