Managing order statuses is critical to running a successful Magento 2 store. Sometimes, you may need to change the order status programmatically rather than manually.
This blog will guide you through the steps to Programmatically Change Order Status in Magento 2.
Whether you need to update orders based on certain conditions or automate the process, this tutorial will help you achieve your goals efficiently.
Steps to Change Order Status Programmatically in Magento 2
1. Load the Order:
To change the order status, you first need to load the order using its ID. You can do this using the \Magento\Sales\Api\OrderRepositoryInterface interface.
Now, create the Observer file in the Observer directory: Use Magento\Sales\Api\OrderRepositoryInterface; $orderId = 123; // replace with your order ID $orderRepository = $objectManager->create(OrderRepositoryInterface::class); $order = $orderRepository->get($orderId); |
2. Set the New Status:
Once the order is loaded, you can set the new status using the setState and setStatus methods.
Now, create the Observer file in the Observer directory: $newStatus = 'custom_status'; // replace with your custom status code $order->setState($newStatus)->setStatus($newStatus); |
3. Save the Order:
After setting the new status, save the order to apply the changes.
Now, create the Observer file in the Observer directory: $orderRepository->save($order); |
4. Complete Example:
Here's a complete example that changes the order status programmatically:
Now, create the Observer file in the Observer directory: use Magento\Sales\Api\OrderRepositoryInterface; $orderId = 123; // replace with your order ID $newStatus = 'custom_status'; // replace with your custom status code $orderRepository = $objectManager->create(OrderRepositoryInterface::class); $order = $orderRepository->get($orderId); $order->setState($newStatus)->setStatus($newStatus); $orderRepository->save($order); |
Conclusion:-
Thank you for coming to the end of our blog. Via this article, I hope that Magento stores can now find a solution for updating their created orders status.
Magento 2 order status promised to bring great improvement in updating order status, Managing and updating orders status easier and more convenient than ever!