To copy data from the sales_order table to the sales_order_grid table using a virtualType in Magento 2, you can create a virtual type that extends the Magento\Sales\Model\ResourceModel\Grid class and adds your custom column to the grid table. Here’s how you can achieve this:

Step 1 : Create Module:

Create a new module directory in app/code directory of your Magento installation. Let’s name it Vendor_Module.

Step 2 : Module Registration:

Create registration.php file in app/code/Vendor/Module with the following content:

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

Step 3 : Module Declaration:

Create module.xml file in app/code/Vendor/Module/etc directory with the following content:

<?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="Vendor_Module" setup_version="1.0.0"/>
</config>

Step 4 : Database Schema:

Create db_schema.xml file in app/code/Vendor/Module/etc directory to define the database schema. Replace last_status_changed_date with the actual name of your custom column:

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="sales_order" resource="sales">
        <column xsi:type="timestamp" name="last_status_changed_date" nullable="true" comment="Last Status Changed Date"/>
    </table>
    <table name="sales_order_grid" resource="sales" extends="sales_order">
        <column xsi:type="timestamp" name="last_status_changed_date" nullable="true" comment="Last Status Changed Date"/>
    </table>
</schema>

Step 5 : Virtual Type Configuration:

Create a di.xml file in the etc directory of your module (app/code/Vendor/Module/etc/di.xml) with the following content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="Vendor\Module\Model\ResourceModel\Order\Grid" type="Magento\Sales\Model\ResourceModel\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="last_status_changed_date" xsi:type="string">sales_order.last_status_changed_date</item>
            </argument>
        </arguments>
    </virtualType>
</config>

Replace Vendor\Module with your actual module name and last_status_changed_date with the name of your custom column.

If you don’t know how to add the custom columns to the sales order grid, then please follow this post.

How to export the admin grid in the current timezone

Thank you so much for taking the time to read my article.

5/5 - (1 vote)