Magento 2.3.1 – Set Order Attribute via Order Create API

attributesmagento2magento2.3.1ordersrest api

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.

Best Answer

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;
    }


 }
Related Topic