how can we create custom order attribute programatically using data-patch in magento 2.4.6 ? I know how to create this customer attribute for order using install schema but currently I am using magento 2.4.6 version so as per standards I wanted to create the same by using data-patch. Can you suggest how to achieve the same by using data-patch
1 Answer
You dont need a patch for that, you can simply use db_schema.xml for that. There you can define new columns in the sales_order table (and/or in the sales_order_grid table, to use it in your order grid). You may also want to create that attribute in your quote.
Here is an example of the
Vendor/Module/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="default" engine="innodb">
<column xsi:type="varchar" name="your_custom_attribute" nullable="true" length="40" comment="Your custom attribute"/>
</table>
<table name="sales_order" resource="default" engine="innodb">
<column xsi:type="varchar" name="your_custom_attribute" nullable="true" length="40" comment="Your custom attribute"/>
</table>
<table name="sales_order_grid" resource="default" engine="innodb">
<column xsi:type="varchar" name="your_custom_attribute" nullable="true" length="40" comment="Your custom attribute"/>
</table>
</schema>
If you want to show that attribute in your order grid, you also have to add a virtual type to your
Vendor/Module/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="joins" xsi:type="array">
<item name="your_custom_attribute" xsi:type="array">
<item name="table" xsi:type="string">sales_order</item>
<item name="origin_column" xsi:type="string">entity_id</item>
<item name="target_column" xsi:type="string">entity_id</item>
</item>
</argument>
<argument name="columns" xsi:type="array">
<item name="your_custom_attribute" xsi:type="string">sales_order.your_custom_attribute</item>
</argument>
</arguments>
</virtualType>
</config>
and add an ui component to show your new column in the order grid Vendor/Module/view/adminhtml/ui_component/sales_order_grid.xml:
<?xml version="1.0"?>
<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="your_custom_attribute">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item
name="label"
xsi:type="string"
translate="true">
Your custom attribute
</item>
</item>
</argument>
</column>
</columns>
</listing>