programatically cancel the order using order id - Magento 2
Even though using the OrderFactory
would work, save
and load
methods are deprecated soon, you should use service contracts instead.
So you can use Magento/Sales/Api/OrderManagementInterface
:
First inject an instance in your class constructor:
protected $orderManagement;
public function __construct(
...
\Magento\Sales\Api\OrderManagementInterface $orderManagement,
....
) {
....
$this->orderManagement = $orderManagement;
....
}
Then use the following:
$this->orderManagement->cancel($orderId);
use \Magento\Sales\Model\OrderFactory
by injecting in the constructor, like below : to cancel the order programmatically
protected $_orderFactory;
public function __construct(
\Magento\Sales\Model\OrderFactory $orderFactory
){
$this->_orderFactory = $orderFactory;
}
public function execute()
{
$orderId = '1234543343'; // your order id
$order = $this->_orderFactory->create()->load($orderId);
$order->cancel()->save();
}