I need to write data to an extension attribute after the order is created from within the admin panel. The extension attribute is the admin user's first and last name. How do I intercept this the right way?
1 Answer
You can use an admin authentication session for this:
An example with a plugin for \Magento\Sales\Api\OrderManagementInterface
:
Acme/StackExchange/Plugin/Sales/Api/OrderManagementInterfacePlugin.php
<?php
declare(strict_types=1);
namespace Acme\StackExchange\Plugin\Sales\Api;
use Magento\Backend\Model\Auth\Session as AuthSession;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderManagementInterface;
class OrderManagementInterfacePlugin
{
/**
* @var AuthSession
*/
protected $authSession;
public function __construct(
AuthSession $authSession
) {
$this->authSession = $authSession;
}
public function afterPlace(
OrderManagementInterface $subject,
OrderInterface $result,
OrderInterface $order
): OrderInterface {
if ($this->authSession->getUser()) {
// the order placed by admin
$firstName = $this->authSession->getUser()->getFirstName();
$lastName = $this->authSession->getUser()->getLastName();
// your logic here
}
return $result;
}
}