Add Order Attribute to Custom Attributes on Magento 2 Rest API?
Step 1: Create new column and set value for the existing order
Firstly, you need to create a new column in table sales_order in your installer file
$setup->getConnection()->addColumn($setup->getTable('sales_order'), 'order_attribute', 'varchar(1)');
In this post, we named it “order_attribute”.
Step 2: Create extension_attributes.xml file
Next, you have to create a file {vendor}\{module}\etc\extension_attributes.xml in the extension folder with following content:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd"> <extension_attributes for="Magento\Sales\Api\Data\OrderInterface"> <attribute code="order_attribute" type="string" /> </extension_attributes> </config>
You have to create file extension_attributes.xml to add the custom attribute because Magento 2 doesn’t accept to add a new field in the response on the Rest API
Step 3: Create observe
In this step, you need to create observer for event ‘sales_order_load_after’ through the file {vendor}\{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_load_after"> <observer name="sales_order_load_order_attribute" instance="{Vendor}\{Module}\Observer\Sales\OrderLoadAfter" /> </event> </config>
Step 4: Create a file to handle this event
Create a file {vendor}\{module}\Observer\Sales\OrderLoadAfter.php to handle the event ‘sales_order_load_after’ which is declared above
<?php namespace {Vendor}\{Module}\Observer\Sales; use Magento\Framework\Event\ObserverInterface; class OrderLoadAfter implements ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $order = $observer->getOrder(); $extensionAttributes = $order->getExtensionAttributes(); if ($extensionAttributes === null) { $extensionAttributes = $this->getOrderExtensionDependency(); } $attr = $order->getData('order_attribute'); $extensionAttributes->setOrderAttribute($attr); $order->setExtensionAttributes($extensionAttributes); } private function getOrderExtensionDependency() { $orderExtension = \Magento\Framework\App\ObjectManager::getInstance()->get( '\Magento\Sales\Api\Data\OrderExtension' ); return $orderExtension; } }
last step is executing these commands
php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush