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 senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.