How to Programmatically Add a Custom Order Attribute in Magento 2

How to Programmatically Add a Custom Order Attribute in Magento 2

Learn how to programmatically add a custom order attribute in Magento 2 using UpgradeData scripts, observers, and UI components. This step-by-step guide walks you through defining the attribute, assigning its value during checkout, updating the sales order grid, and displaying it in the admin panel—perfect for extending Magento’s default functionality with custom data fields.

How to Programmatically Add a Custom Order Attribute in Magento 2

To add a custom order attribute programmatically in Magento 2, follow these steps. This process allows you to collect additional customer data during checkout, enhancing order management and customer insights.

Step 1: Create the UpgradeData Script

Define the new attribute in the UpgradeData.php file located at app/code/Company/Module/Setup/UpgradeData.php:

namespace Company\Module\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;

use Magento\Framework\Setup\ModuleDataSetupInterface;

use Magento\Framework\Setup\ModuleContextInterface;

use Magento\Sales\Setup\SalesSetupFactory;

class UpgradeData implements UpgradeDataInterface

{

private $salesSetupFactory;

public function __construct(SalesSetupFactory $salesSetupFactory)

{

$this->salesSetupFactory = $salesSetupFactory;

}

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)

{

if (version_compare($context->getVersion(), '1.0.1', '<')) {

$salesSetup = $this->salesSetupFactory->create(['setup' => $setup]);

$salesSetup->addAttribute(

'order',

'custom_order_attribute',

[

'type' => 'varchar',

'length' => 255,

'visible' => false,

'required' => false,

'grid' => true

]

);

}

}

}

This script adds a new attribute named custom_order_attribute to the sales_order and sales_order_grid tables.

Step 2: Set Attribute Value Using an Observer

Create an observer to set the value of the custom attribute when an order is placed.

events.xml: Place this file in app/code/Company/Module/etc/events.xml:

<?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_order_place_after">

<observer name="set_custom_order_attribute" instance="Company\Module\Observer\SetOrderAttribute" />

</event>

</config>

SetOrderAttribute.php: Create this file in app/code/Company/Module/Observer/SetOrderAttribute.php:

namespace Company\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

use Magento\Framework\Event\Observer;

class SetOrderAttribute implements ObserverInterface

{

public function execute(Observer $observer)

{

$order = $observer->getEvent()->getOrder();

$order->setData('custom_order_attribute', 'Your Value');

$order->save();

}

}

This observer sets the value of custom_order_attribute to "Your Value" when an order is placed.

Step 3: Synchronize sales_order and sales_order_grid Tables

Ensure that the custom attribute is available in the order grid by updating the di.xml file.

di.xml: Place this file in app/code/Company/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" type="Magento\Sales\Model\ResourceModel\Grid">

<arguments>

<argument name="columns" xsi:type="array">

<item name="custom_order_attribute" xsi:type="string">sales_order.custom_order_attribute</item>

</argument>

</arguments>

</virtualType>

</config>

This configuration ensures that the custom_order_attribute is included in the sales_order_grid table.

Step 4: Display the Custom Attribute in the Admin Grid

To show the custom attribute in the admin sales order grid, update the UI component XML.

sales_order_grid.xml: Place this file in app/code/Company/Module/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="custom_order_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">Custom Order Attribute</item>

</item>

</argument>

</column>

</columns>

</listing>

This adds a new column labeled "Custom Order Attribute" to the sales order grid in the admin panel.

Tailwind CSS vs. Bootstrap: A Quick Comparison

Step Action File Path
1 Create UpgradeData script app/code/Company/Module/Setup/UpgradeData.php
2 Set attribute value via observer app/code/Company/Module/Observer/SetOrderAttribute.php
3 Synchronize tables app/code/Company/Module/etc/di.xml
4 Display in admin grid app/code/Company/Module/view/adminhtml/ui_component/sales_order_grid.xml

By following these steps, you can programmatically add and manage custom order attributes in Magento 2, enhancing your store's data collection and order processing capabilities.

Tip

To enhance your eCommerce store’s performance with Magento, focus on optimizing site speed by utilizing Emmo themes and extensions. These tools are designed for efficiency, ensuring your website loads quickly and provides a smooth user experience. Start leveraging Emmo's powerful solutions today to boost customer satisfaction and drive sales!

FAQs

What is a custom order attribute in Magento 2?

A custom order attribute is an additional field added to the sales order entity that allows you to store extra information during or after the checkout process.

Why would I add a custom order attribute?

Custom order attributes allow you to collect or store business-specific data such as delivery instructions, referral sources, or internal notes linked to an order.

How do I create a custom order attribute programmatically?

You can create a custom order attribute by writing an upgrade script in your module using the addAttribute method provided by the SalesSetup class.

Where do I define the attribute code?

The attribute code is defined in the UpgradeData.php file inside your module's Setup directory. It’s the key used to reference the attribute in code and in the database.

How can I assign a value to the custom attribute?

You can assign a value to the attribute using an observer that listens to the sales_order_place_after event and sets the data accordingly before saving the order.

How do I display the custom attribute in the order grid?

To display it in the admin order grid, update the sales_order_grid.xml UI component file and make sure the attribute is synced with the sales_order_grid table.

Do I need to modify di.xml to support the attribute?

Yes, you should add your attribute to the virtual type configuration in di.xml so Magento knows to include it in the order grid data source.

Is it possible to make the attribute visible in the admin panel only?

Yes, when defining the attribute, set 'visible' => false and control visibility through your admin UI customization like grid and form components.

Can I use the Object Manager to set attribute values?

Using the Object Manager directly is discouraged. Instead, use dependency injection to access required services and maintain Magento best practices.

Where can I find examples of custom order attributes?

Magento DevDocs, community tutorials, and GitHub repositories often provide working examples of how to add, manage, and display custom order attributes in Magento 2.