Magento – Magento 2 how add extension attribute to order item

extension-attributesmagento2sales-ordersales-order-item

I need to save the extension attribute for Order item. I have tried using plugin with below code, but it is not working for me. I have placed a log inside the method but the method is not working.

<type name="Magento\Sales\Api\OrderItemRepositoryInterface">
    <plugin name="order_item_extension_attr" type="Vendor\CustomModule\Plugin\Model\Test"/>
</type>

public function afterGet(
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItem, 
        \Magento\Sales\Api\Data\OrderItemExtensionInterface $extension = null
    ) {

}

How to save and get order item extension attribute?

Edited:
Used an observer after order saved, stored the order and item extension attributes in db. Which is working fine, but showing the order item values are not showing up in the order view page.

Best Answer

1. If you want to use extension attribute then you must declare extension attribute at app/code/YOurModule/{Modulename}/etc/extension_attributes.xml.

Create 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\OrderItemInterface">
        <attribute code="{fieldname}" type="string" />
    </extension_attributes>
</config>

Assume that field type is varchar/text.

2. Create after plugin on save() method of Magento\Sales\Api\OrderRepositoryInterface while save Order using Magento\Sales\Api\OrderRepositoryInterface:save method.

Related Topic