Skip to content

Magento 2 : How to prevent order cancellation in based on a custom condition?

I have a requirement, where I need to verify a custom condition just before the order cancellation process.

If the condition fails, I need to stop the cancellation and revert the order to its previous state (i.e., prevent the cancellation entirely).

What I tried

  1. Observers

I implemented an observer for the order cancellation event, but observers in Magento cannot stop the action; they only let me inspect the order after the event is triggered. Throwing an exception from an observer doesn’t actually prevent the cancellation.

  1. Plugins

I decided to go with plugins, so I tried:

  • MagentoSalesModelOrder::cancel()
  • MagentoSalesModelRefundOrder

But neither of these plugins seem to execute when I cancel the order from the Magento Admin backend.

My question

Which method/class should I target with a plugin so that I can run my verification logic before the cancellation is processed and prevent it if the condition fails?

Expected flow:

  • Admin clicks Cancel.
  • System checks a specific condition.
  • If the condition is met:Cancel the cancellation process.Restore the order to its previous state (before initiating the refund).
  • If the condition is not met:Proceed with the cancellation and
    continue with the refund process.

Is there a better approach than using a plugin for this scenario?