0

When the magento2.4 order status changes to completed, can I perform an event to process one of my tasks

1 Answer 1

1

As far as I know, there is no such event which observes specific order status complete. Still, you can try with sales_order_state_change_before or sales_order_save_after events.

Solution #1: sales_order_save_after event:

Observer/SalesOrderAfterSave.php

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $order = $observer->getEvent()->getOrder();
    if ($order instanceof \Magento\Framework\Model\AbstractModel) {
       if($order->getState() == 'complete') {
            //Your code here
       }
    }
    return $this;
}

Solution #2: sales_order_state_change_before event:

Observer/SalesOrderStateChangeBefore.php

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $transport = $observer->getEvent()->getTransport();
    if ($transport->getState() == "complete") {
        //Your code here
    }
    return $this;
}

Solution #3 You can try using Plugin also:

etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Api\OrderRepositoryInterface">
        <plugin name="order_state_plugin"
                type="Company\Module\Model\Plugin\OrderStatePlugin"/>
    </type>
</config>

OrderStatePlugin.php

public function afterSave(
    \Magento\Sales\Api\OrderRepositoryInterface $subject,
    $result
) {
    if($result->getState() == Order::STATE_COMPLETE) {
        ......
    }
    return $result;
}

Let me know if it helped.

4
  • I use the sales_order_save_after event and sometimes I miss some orders. Can I use the sales_order_invoice_save_after event? The action I'm going to perform is when the order status changes to completed.
    – sq y
    Dec 12, 2022 at 5:59
  • yes, sales_order_invoice_save_after should work. Dec 12, 2022 at 6:52
  • Thank you,it work!
    – sq y
    Dec 13, 2022 at 3:22
  • @sqy If it worked, could you please accept my answer? Dec 13, 2022 at 4:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.