How to Add Order Attribute Programmatically in Magento 2?

How to Add Order Attribute Programmatically in Magento 2?

How to run a successful eCommerce store? This question is something that store owners keep asking themselves 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. 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 and the more operations you can perform.

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.

order-attributes

Additionally, the extension allows you to restrict the attributes based on customer group.

new-product-attributes

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 Create Order Attribute Programmatically

The following steps will help create 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 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</item>
 </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>
 <item name="label" xsi:type="string" translate="true">Custom Order Attribute</item>
 </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.

Related Articles:

This blog was created with FME's SEO-friendly blog