- etc/di.xml
<type name="Magento\Sales\Api\OrderRepositoryInterface">
<plugin name="order_delivery_date_attribute" type="Vendor\DeliveryDate\Plugin\Model\Order\AddDeliveryDateAttribute" />
</type>
- etc/extension_attributes.xml
<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="delivery_date" type="string"/>
</extension_attributes>
</config>
- Vendor/DeliveryDate/Plugin/Model/Order/AddDeliveryDateAttribute.php
<?php
namespace Vendor\DeliveryDate\Plugin\Model\Order;
use Magento\Sales\Api\Data\OrderSearchResultInterface;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\Data\OrderExtensionFactory;
use Magento\Sales\Api\Data\OrderInterface;
class AddDeliveryDateAttribute
{
/**
* @var OrderFactory
*/
private $orderFactory;
/**
* @var OrderExtensionFactory
*/
private $orderExtensionFactory;
/**
* @param OrderExtensionFactory $extensionFactory
* @param OrderFactory $orderFactory
*/
public function __construct(
OrderExtensionFactory $extensionFactory,
OrderFactory $orderFactory
) {
$this->orderExtensionFactory = $extensionFactory;
$this->orderFactory = $orderFactory;
}
/**
* @param OrderRepositoryInterface $subject
* @param OrderSearchResultInterface $searchResult
* @return OrderSearchResultInterface
*/
public function setMyCustomOrderAttributeData(OrderInterface $order)
{
if ($order instanceof \Magento\Sales\Model\Order) {
$myCustomOrderAttribute = $order->getDeliveryDate();
} else {
$orderModel = $this->orderFactory->create();
$orderModel->load($order->getId());
$myCustomOrderAttribute = $orderModel->getDeliveryDate();
}
$extensionAttributes = $order->getExtensionAttributes();
$orderExtensionAttributes = $extensionAttributes ? $extensionAttributes
: $this->orderExtensionFactory->create();
$orderExtensionAttributes->setDeliveryDate($myCustomOrderAttribute);
$order->setExtensionAttributes($orderExtensionAttributes);
}
/**
* @param OrderRepositoryInterface $subject
* @param OrderSearchResultInterface $searchResult
* @return OrderSearchResultInterface
*/
public function afterGetList(
OrderRepositoryInterface $subject,
OrderSearchResultInterface $orderSearchResult
) {
foreach ($orderSearchResult->getItems() as $order) {
$this->setMyCustomOrderAttributeData($order);
}
return $orderSearchResult;
}
/**
* @param OrderRepositoryInterface $subject
* @param OrderInterface $order
* @return OrderInterface
*/
public function afterGet(
OrderRepositoryInterface $subject,
OrderInterface $resultOrder
) {
$this->setMyCustomOrderAttributeData($resultOrder);
return $resultOrder;
}
}
The order attribute will be shown via the API call <URL>/rest/default/V1/orders/<order_id>
'delivery_date' attribute value will be displayed
Top comments (0)