I'll want to update an orderStatus in craft commerce after the order is complete for a specific (digital) pruduct type. To send an extra email with download links, confirm email is already send based on the default status. To do that I'll use an event like this, but how I'll get the orderId from the event, looks like this id is only in the private _lineItems. So I'll can't use $event->sender->orderId
.
/**
* update status
*
* @return void
*/
Event::on(
Order::class,
Order::EVENT_AFTER_COMPLETE_ORDER,
function (Event $event) {
$order = \craft\commerce\Plugin::getInstance()->getOrders()->getOrderById($event->sender->orderId);
if ($order) {
$order->orderStatusId = 5; // order status ebooks send is 5
$result = Craft::$app->getElements()->saveElement($order);
}
}
);
==== UPDATE ====
Final working solution:
/**
* Update orderstatus to send downloads mail for digital products
*
* @return void
*/
Event::on(
Order::class,
Order::EVENT_AFTER_COMPLETE_ORDER,
function (Event $event) {
$order = $event->sender;
if (!$order->id) {
return;
}
$digitalProductTypeIds = [8,9,10];
$digitalStatusId = 5;
$updateStatus = false;
// Loop through lineitems and search for digital products based on productype
foreach ($order->lineItems as $product) {
if( isset($product->snapshot['product']) && in_array($product->snapshot['product']['typeId'],$digitalProductTypeIds) )
{
$updateStatus = true;
break;
}
}
// Update orderstatus id if digital products present in the order
if($updateStatus){
$order->orderStatusId = $digitalStatusId;
Craft::$app->getElements()->saveElement($order);
}
}
);