Expert Solution to Get Current Order Status And New Order Status in Magento 2
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
123<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/
12345678910111213141516<?phpnamespace 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.
Any doubts? Please mention them in the Comments section below. I’d be glad to help you out asap.
Do share the solution with fellow Magento developers via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How To Add CSS & Javascript Files To CMS Pages In Magento 2
How To Configure Magento 2 Email Header Template
Next