3

After Payment is accepted, I need to update the order status to "Completed" from the page controller.

How do I do this, on Drupal 8?

I find no documentation about this; there is an example for Drupal 7.

// Updating Order status.
$orderObj = commerce_order_load($orderID);
commerce_order_status_update($orderObj, 'canceled', TRUE, 'Order Voided');
$orderObj->log = 'Order cancelled programatically';
commerce_order_save($orderObj); 

4 Answers 4

9

You want to use the State Machine methods of the Commerce Order class.

It would be something like this, but it will depend on what you called your order states.

$order_state = $orderObj->getState();
$order_state_transitions = $order_state->getTransitions();
$order_state->applyTransition($order_state_transitions['complete']);

$orderObj->save();

If you aren't sure, you can always check the $order_state_transitions array to see what options you have.

3
  • I think the state that needs to be set (default setup) is "placed"; also, i think you are missing a line where you need to assign the $order_state back to the Order before saving it.
    – liquidcms
    Commented Mar 27, 2020 at 20:52
  • No, you don't. Setting the state yourself would go against the pattern. You are welcome to post your own answer.
    – Chance G
    Commented Apr 2, 2020 at 21:55
  • Yes, my idea was wrong. I posted a similar question (and answered it) here: drupal.stackexchange.com/questions/292291/…
    – liquidcms
    Commented Apr 3, 2020 at 6:00
2

I think you are looking to "place" the order. You need to subscribe to the Event handler for this event: commerce_order.order.paid

and with this handler code:

  public function paymentCompletedHandler($event) {
    $order = $event->getOrder();
    $order->getState()->applyTransitionById('place');
    return;
  }
0

This code did the job for me. You need to know the ID of the transition. In my case, it's 'cancel'

$order = \Drupal\commerce_order\Entity\Order::load($order_id);
$order_state = $order->getState();
$order_state->applyTransitionById('cancel');
$order->save();
-2

You can simply use set method.

$order->set('state', 'completed');
$order->save();
1
  • 2
    this will bypass state transitions and break commerce_stock, potentially skip notifications, and other modules that hook into state transitions Commented Feb 4, 2020 at 16:27

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.