Magento 2 is an insanely flexible platform that allows us, developers, to satisfy the crazy clients’ requirements!
Isn’t it?
I recently faced a similar situation where the client wanted to perform a specific action when the order status is changed. To do so, I had to get current order status and new order status in Magento 2.
In this blog, I have posted that solution straightaway for the developers to save themselves from what I went through for the solution.
You can use the below code to implement, for example, a feature where a popup displays when the order state is changed from placed to processing saying that you can use this coupon code, or a feature to calculate and return tax amount when an order is placed and completed.
Get the previous and next order status in Magento 2 to perform any action when the order status is changed, using the following code:
Steps to Get Current Order Status and New Order Status in Magento 2
Create di.xml file at app/code/Vendor/Extension/etc/ folder
<type name="Magento\Sales\Model\ResourceModel\Order"> <plugin name="order_state_plugin" type="Vendor\Extension\Plugin\OrderPlugin"/> </type>
Create OrderPlugin.php file at app/code/Vendor/Extension/Plugin/
<?php namespace Vendor\Extension\Plugin; use Magento\Sales\Model\ResourceModel\Order; class OrderPlugin { public function afterSave( Order $subject, $result, $object ) { $oldData = $object->getOrigData('status'); $newData = $object->getData('status'); \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info(print_r("Old Data = $oldData",true)); \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info(print_r("New Data = $newData",true)); } }
That’s it.
You can also make order status visible on frontend in Magento 2 by tweaking the backend configuration.
Learn here to get order status label in Magento 2.
Do share the solution with fellow Magento developers via social media.
Thank you.