I am using Craft Commerce and want to edit the order after it has been completed by the customer. For this I am using the EVENT_AFTER_COMPLETE_ORDER event.
Event::on(
Order::class,
Order::EVENT_AFTER_COMPLETE_ORDER,
function (Event $event) {
$order = $event->sender;
$order = Order::find()->id($order->id)->one();
if (!$order) {
throw new \Exception('Invalid order ID: ' . $this->id);
}
if ($order->shippingMethodHandle === 'DHL' && !$order->parcelNumber) {
$order->setFieldValue("parcelNumber", 5005);
if (!Craft::$app->getElements()->saveElement($order)) {
Craft::error('Automatic creation of Mikropakket label has failed.', __METHOD__);
}
}
}
);
I can correctly read the values in the $order variable but saving the parcelNumber does not seem to work. There are no errors and when I debug with Xdebug I can see that the saveElement method is being called. When looking at the order the parcelNumber field is empty.
Does anyone have any experience with this?