sync fields from sales_order to sales_order_grid

For example, I have a column named ‘delivery_comment’, and it has been added to these three tables(quote, sales_order, sales_order_grid).

etc/db_schema.xml

<?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="quote" resource="checkout">
        <column xsi:type="varchar"  name="delivery_comment" length="255" nullable="false" />
    </table>
    <table name="sales_order_grid" resource="sales">
        <column xsi:type="varchar"  name="delivery_comment" length="255" nullable="false" />
    </table>
    <table name="sales_order" resource="sales">
        <column xsi:type="varchar"  name="delivery_comment" length="255" nullable="false" />
    </table>
</schema>

I want to copy delivery_comment value from quote to sales_order.

My solution is using sales_model_service_quote_submit_before event.

etc/events.xml

<?xml version="1.0" encoding="UTF-8"?>
<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="delivery_comment_save" instance="VendorName\ModuleName\Observer\SaveDeliveryDateToOrderObserver"/>
    </event>
</config>
<?php
namespace VendorName\ModuleName\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class SaveDeliveryDateToOrderObserver implements ObserverInterface
{
    public function execute(EventObserver $observer)
    {
        $order = $observer->getOrder();
        $quote = $observer->getQuote();
        $order->setDeliveryComment($quote->getDeliveryComment());
    }
}

I tried fieldset.xml, but no luck.

Next, I want to copy delivery_comment value from sales_order to sales_order_grid.

etc/di.xml

<?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="Magento\Sales\Model\ResourceModel\Order\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="delivery_comment" xsi:type="string">sales_order.delivery_comment</item>
            </argument>
        </arguments>
    </virtualType>
</config>

All done!

发表评论

电子邮件地址不会被公开。 必填项已用*标注