Magento – Add extension attribute to Order

extension-attributesmagento2sales-order

I want to add custom field "comment" to the order as an extension attribute. So, the first, I have added this column to following tables in database: "quote" and "sales_order".

It's my xml file:

<?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="comment" type="string"/>
    </extension_attributes>
</config>

It's my observer ("sales_order_save_after"), where I'm trying to set "comment":

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Sales\Api\OrderRepositoryInterface;

class SaveComment implements ObserverInterface
{
    protected $_rep;

    public function __construct(OrderRepositoryInterface $rep)
    {
        $this->_rep = $rep;
    }

    public function execute(Observer $observer)
    {
        $order = $observer->getEvent()->getData('order');
        $ext = $order->getExtensionAttributes();
        $ext->setComment('Hi, Magento!');
        $order->setExtensionAttributes($ext);
        $this->_rep->save($order);
    }
}

And it works, but doesn't add any attributes to database, so when I try to get it in another place with:

$comment = $order->getExtensionAttributes()->getComment();

I get null.
Please, help me.

Best Answer

You need to add the below plugin to di.xml

<type name="Magento\Sales\Api\OrderRepositoryInterface">
    <plugin name="get_order_comment" type="Vendor\Sample\Plugin\OrderGet"/>
</type>

Now add the plugin to add the data to the api

class OrderGet {

    protected $_orderExtensionFactory;

    public function __construct(
        \Magento\Sales\Api\Data\OrderExtensionFactory $orderExtensionFactory
    ) {
        $this->_orderExtensionFactory = $orderExtensionFactory;
    }

    public function afterGet(
        \Magento\Sales\Api\OrderRepositoryInterface $subject,
        \Magento\Sales\Api\Data\OrderInterface $order
    ) {
        $extensionAttributes = $order->getExtensionAttributes();
        $orderExtension = $extensionAttributes ? $extensionAttributes : $this->_orderExtensionFactory->create();

        $comment = {write the logic to get the comment. e.g. $order->getComment()}
        $orderExtension->setComment($comment);

        $order->setExtensionAttributes($orderExtension);

        return $order;
    }
}