How to Add Order Attribute Programmatically in Magento 2?
How to run a successful eCommerce store? This question is something every store owner keeps asking themself throughout the day. Do you know the answer? Unfortunately, there is no fixed answer to this question since there are many factors which need to be considered. These can be collectively termed as success factors for an online store.
For instance, product quality is directly related to customer satisfaction. If a store is offering poor quality, customers will simply opt for a competitor store. After all, no one buys a poor-quality product purposely because even if their budget is low, customers look for value for money. Similarly, marketing influences the customer buying behaviour.
Effective marketing strategies can compel a lead to complete the purchase. While marketing and product quality are important, data is fast becoming the top success factor. If you search a little about the growing importance of data, you’ll come to know that data is the new oil. Indeed, the digital age is characterised by data. The more data you have, the better you understand your customers.
It is the reason store owners want to collect as much data from customers as possible. This is where attributes come into play. Custom order attributes, customer attributes, and product attributes are created for this very purpose. They are the most popular operations in any ecommerce store. We have already written on creating customer attributes and product attributes programmatically in Magento 2.
Here, we will see how to add custom order attributes programmatically.
Ready Made Solution: Magento 2 Add Custom Order Attribute
About the Extension
The above extension makes adding order attribute easy and hassle-free. Users can add 12 different types of order attributes, including data, image, and file. The below image provides information about the other attributes.
Additionally, the extension allows you to restrict the attributes based on customer group.
For instance, you can prevent users from seeing the attributes unless they are logged in. Lastly, you can determine the order of each attribute. This allows you to place most important attributes on top of the list.
Magento 2 Add Order Attribute Programmatically
The following steps will help add order attribute programmatically in Magento 2:
Step 1: Create an UpgradeData File
File Path: app/code/Company/Mymodule/Setup/UpgradeData.php
?php
namespace Company\Mymodule\Setup;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Sales\Setup\SalesSetupFactory;
/**
* Class UpgradeData*/
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' => 5,
'visible' => false,
'required' => false,
'grid' => true
]
);
}
}
}
This will create the Magento 2 custom order attribute ‘custom_order_attribute’ in the sales_order table and sales_order_grid table.
Step 2: Save the Order Attribute Using Observer
Next, you want to set value for this attribute. We will use sales_order_save_after event to set value when the order is created. So we will create new events.xml file in Company/Mymodule/etc/events/xml with the following content.
?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_save_after">
observer instance="Company\Mymodule\Observer\Sales\SetOrderAttribute" name="set_order_attribute"/>
/event>
/config>
And the actual code for this will be in Company\Mymodule\Observer\Sales\SetOrderAttribute.php with the following content.
?php
namespace Company\Mymodule\Observer\Sales;
class SetOrderAttribute implements \Magento\Framework\Event\ObserverInterface
{
protected $productRepository;
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Catalog\Model\ProductRepository $productRepository
) {
$this->logger = $logger;
$this->productRepository = $productRepository;
}
public function execute(
\Magento\Framework\Event\Observer $observer
) {
$order= $observer->getData('order');
$order->setCustomAttribute("Yes");
$order->save();
}
}
We set the value of the custom order attribute and saved the order object.
Step 3: Sync sales_order table and sales_order_grid table
Now, we need to tell Magento to copy values from sales_order to sales_order_grid table when a new order is created. That is done by di.xml file. Create di.xml in Company/Mymodule/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">
!--Sync the sales_order table and sales_order_grid-->
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
/argument>
/arguments>
/virtualType>
/config>
Step 4: Show Custom Order Attribute in Grid
Next, we need to tell the sales_order_grid.xml UI component to create a column for our new attribute. Create a new xml file in Company/Mymodule/view/adminhtml/ui_component/sales_order_grid.xml with the following content.
?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 name="label" xsi:type="string" translate="true">Custom Order Attribute
/item>
/argument>
/column>
/columns>
/listing>
Now you will see the column Custom Order Attribute in the admin grid with value Yes.
Final Thoughts on Magento 2 Add Order Attribute Programmatically
This concludes our article on adding order attribute programmatically. If you have any issue in adding order attribute programmatically in Magento 2, then feel free to contact our support team for a quick fix.
FAQs About Magento 2 Add Order Attribute Programmatically
What is a Magento 2 custom order attribute?
The Magento 2 custom order attribute is a field which allows merchants to gather additional information about a customer order. The purpose of the Magento 2 order attributes is to provide personalised services, help with tracking, or streamline internal order management.
After adding a Magento 2 custom order attribute, do I need to flush the cache?
We recommend flushing the cache after making any change in Magento 2, including when you add the Magento 2 order attributes. It ensures that the desired changes are reflected in the store right away.
Is there an extension to add Magento 2 custom order attribute rather than do it programmatically?
If you are not comfortable with Magento 2 add order attribute programmatically, you can use an extension for this purpose. For example, the Magento 2 Custom Order Attribute by FME offers a straightforward way to add custom attributes without any coding knowledge. Merchants can choose from up to 12 different types of fields. Apart from this, merchants can restrict the attributes based on customer groups and store views.
Do Magento 2 order attributes degrade store performance?
No, the Magento 2 custom order attributes does not slow down your store’s performance. However, adding too many custom attributes can be problematic and can lead to database indexing issues. Therefore, it is best to use an extension since it is optimised for performance.
What Magento 2 order attributes can I create?
The extension allows you to create order attributes from up to 12 different fields, including:
- Text Field
- Dropdown
- Checkbox
- File Upload
Related Articles:
This blog was created with FME's SEO-friendly blog