How to programmatically change order status

Components

Changing the order state in Drupal Commerce 2.x like this:

$order->set('state', 'canceled');
$order->save();

is not a good idea because you are not dispatching transition events. And some modules depend on those events. The proper way to change the order state is to apply state transition like this:

$order = \Drupal::entityTypeManager()
  ->getStorage('commerce_order')
  ->load(1);
$order->getState()->applyTransitionById('cancel');
$order->save();

You can find the list of transition IDs in the workflows file.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.