How To Add Extension Attribute To Order In Magento 2?
How To Add Extension Attribute To Order In Magento 2?
Extension attributes are new in Magento 2. They are used to extend functionality and often use more complex data types than custom attributes. These attributes do not appear in the Admin.
Extension attributes allow you to add additional data to existing entities like orders without modifying the core code. Follow step by step guide on how to do this:
How To Add Extension Attribute To Order In Magento 2?
Create custom module
app/code/Latest/Blog
1.Create registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Latest_Blog', __DIR__ );
2.Create a etc/module.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Latest_Blog" setup_version="1.0.0"/> </config>
3.Create a file named extension_attributes.xml
<?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="latest_blog" type="string"/> </extension_attributes> </config>
4.Create a data provider
app/code/Latest/Blog/Model/CustomAttributeDataProvider.php
<?php namespace Latest\Blog\Model; use Magento\Sales\Api\Data\OrderExtensionFactory; use Magento\Sales\Api\Data\OrderInterface; class CustomAttributeDataProvider implements \Magento\Sales\Api\OrderExtensionDataProviderInterface { /** * @var OrderExtensionFactory */ private $extensionFactory; public function __construct( OrderExtensionFactory $extensionFactory ) { $this->extensionFactory = $extensionFactory; } /** * @param OrderInterface $entity * @return OrderInterface */ public function getExtensionAttributes(OrderInterface $entity) { $extensionAttributes = $entity->getExtensionAttributes(); if ($extensionAttributes === null) { $extensionAttributes = $this->extensionFactory->create(); $entity->setExtensionAttributes($extensionAttributes); } return $extensionAttributes; } }
5.Create di.xml
app/code/Latest/Blog/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"> <type name="Magento\Sales\Api\Data\OrderExtensionInterface"> <plugin name="Latest_blog_order_extension" type="Latest\Blog\Model\CustomAttributeDataProvider" sortOrder="10"/> </type> </config>
6.Add the attribute to orders
$order->getExtensionAttributes()->setCustomAttribute('custom_value'); $customAttribute = $order->getExtensionAttributes()->getCustomAttribute();