2

I've created a couple of order attributes using the method described here (https://www.yereone.com/blog/magento-2-how-to-add-new-order-attribute/) in order to save some data that is passed into Magento 2 via our legacy application.

Is it possible to pass these values over when creating an order via the API? or is there a better way to achieve the same result? I'm using Magento 2.3 if that has any impact.

3

First read this below articles:

If you want to add a field them you need to use extension_atttibutes

Extension attribute gives the facility to add a new field to existing API point.

The fields which you have created using https://www.yereone.com/blog/magento-2-how-to-add-new-order-attribute/) to be used as an extension attribute for data Magento\Sales\Api\Data\OrderInterface.

So, create etc/extension_attributes.xml at your module folder

<?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="is_important" type="string" /> <!-- type defined as string -->
    </extension_attributes>
</config>

Save field to order table

And as you have created the column to an existing order table, So save the create before plugin on \Magento\Sales\Api\OrderRepositoryInterface::save().

<?php

namespace Yereone\NewOrderAttribute\Plugin;

use Magento\Framework\Exception\CouldNotSaveException;

class OrderSave
{

...

    public function beforeSave(
        \Magento\Sales\Api\OrderRepositoryInterface $subject,
        \Magento\Sales\Api\Data\OrderInterface $resultOrder
    ) {

    $extensionAttributes = $resultOrder->getExtensionAttributes();
        if (null !== $extensionAttributes) {
           $extensionAttributes->getIsImportant()->getValue();
           $resultOrder->setIsImportant( $extensionAttributes->getIsImportant()->getValue());   
    }
        return $resultOrder;
    }


 }
| improve this answer | |
  • Seems like a sensible approach, my only comment would be if I save data as an extension attribute AND then save it to the order table fields I've added am I not just duplicating data? Is there any way to show extension attributes in the sales order grid? – Matthew Jul 24 '19 at 10:57
  • @amith: thanks a lot for sharing the fooman link. More. It is more clear compared to the dev docs. – Sukeshini Jan 24 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.