magento 2 cancel order programmatically,magento cancel order frontend,magento 2 cancel order frontend,magento 2 cancel order extension,cancel order magento 2,magento 2 edit order,magento 2 delete orders,magento cancel order programmatically,Page navigation

hi guys if you wanna Cancel orders in magento 2 programatically then please read this post till end. I implemented the module in magento 1 in which I wanna cancel the pending order from customer my account page.my current code that i implemented in magento 1 is below:

$order = Mage::getModel('sales/order')->load($orderId);
$order_status=$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();

As you know magento is now moved to version 2 so I implemented the same functionality in magento 2. To do this. You should use API (more about magento2 API concepts) for that, example how to use it in your class:

<?php

use Magento\Sales\Api\OrderManagementInterface;

class A
{
    /**
     * @var OrderManagementInterface
     */
    private $orderManagement;

    /**
     * @param OrderManagementInterface $orderManagement
     */
    public function __construct(OrderManagementInterface $orderManagement)
    {
        $this->orderManagement = $orderManagement;
    }

    public function cancelOrderOne()
    {
        $orderId = 1;
        $isCanceled = $this->orderManagement->cancel($orderId);
    }
}

?>