1

When an order is submitted, I need to write data to extension attributes. I need to either create an event observer or plugin. How do I do this the right way?

1 Answer 1

2

There is 2 way to handle order place

1. Event

Acme/StackExchange/etc/events.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="acme_stackexchange_observer_sales_order_place_after"
                  instance="Acme\StackExchange\Observer\Sales\OrderPlaceAfter"/>
    </event>
</config>

Acme/StackExchange/Observer/Sales/OrderPlaceAfter.php

<?php
declare(strict_types=1);

namespace Acme\StackExchange\Observer\Sales;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order;

class OrderPlaceAfter implements ObserverInterface
{
    /**
     * @inheritDoc
     */
    public function execute(Observer $observer)
    {
        /** @var Order $order */
        $order = $observer->getEvent()->getData('order');
        // your logic here
    }
}

2. Plugin

Acme/StackExchange/etc/di.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Api\OrderManagementInterface">
        <plugin name="Acme_StackExchange_Plugin_Sales_Api_OrderManagementInterfacePlugin"
                type="Acme\StackExchange\Plugin\Sales\Api\OrderManagementInterfacePlugin" sortOrder="10"/>
    </type>
</config>

Acme/StackExchange/Plugin/Sales/Api/OrderManagementInterfacePlugin.php

<?php
declare(strict_types=1);

namespace Acme\StackExchange\Plugin\Sales\Api;

use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderManagementInterface;

class OrderManagementInterfacePlugin
{
    public function afterPlace(
        OrderManagementInterface $subject,
        OrderInterface $result,
        OrderInterface $order
    ): OrderInterface {
        // your logic here

        return $result;
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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