Magento 2 cancel order from myaccount page

1.5k Views Asked by At

Cancelling order in magento 2 programatically:

I implemented the module in magento 1 in which I will cancel the pending order from customer my account page.

Please refer to the code below which I implemented in the magento 1:

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

I want to implement the same functionality in magento 2. Does anyone know how to implement it?

I loaded the order with order id in magento 2, but am unable to cancel the order.

2

There are 2 best solutions below

2
On BEST ANSWER

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);
    }
}
0
On

Please look at the code below, it will also validate the user associations for the order also

<?php
 Nmaespace\Modulename\Controller\Action;

class Cancelorder  extends \Magento\Framework\App\Action\Action
{
  protected $orderManagement;
  public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Sales\Api\OrderManagementInterface $orderManagement

) {
    $this->orderManagement = $orderManagement;
    parent::__construct($context); 
}

public function execute()
{
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $customerSession = $objectManager->get('Magento\Customer\Model\Session');
        if(!$customerSession->isLoggedIn()) {
                $this->_redirect('/');
                die;
        }

        /*get request params */
        $get_customer_id = $customerSession->getCustomer()->getId();

        $get_order_id = $this->getRequest()->getParam('order_id');
        /*get request params */
        //die;
        $order = $objectManager->create('Magento\Sales\Model\Order')->load($get_order_id);
        $getcustomerid = $get_customer_id;
        $orderdata  = $order->getData();
        $order_status = $orderdata["status"];
        //print_r($orderdata);
        $cus_id =  $orderdata["customer_id"];
        if($getcustomerid != $cus_id){
            echo "We cant Cancel this order at this time" ;
            //die("go back");
        }
        if($order_status == "pending"){
            $this->orderManagement->cancel($get_order_id); 
            echo "Order Cancelled successfully" ;
        }
        else{
            echo "We cant Cancel this order at this time" ;

        }
}


}