6

My requirement is programatically change the order status to Canceled by using order id.

How to achieve this?

Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
Bilal Usean
  • 9,977
  • 14
  • 75
  • 122

3 Answers3

19

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);
Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
  • Hi @Raphael http://magento.stackexchange.com/questions/164002/magento-2-how-to-refund-or-cancel-paypal-order – Jackson Mar 21 '17 at 08:23
  • Please check here it works perfect for me
    http://magentocodes.blogspot.in/2017/10/how-to-cancel-order-programatically-in.html
    – Rohit Goel Oct 16 '17 at 08:32
3

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();   
}
Manashvi Birla
  • 8,833
  • 9
  • 27
  • 53
-1

I tried below solution and it works perfect

http://magentocodes.blogspot.com/2017/10/how-to-cancel-order-programatically-in.html

Rohit Goel
  • 321
  • 3
  • 10