Magento 2 Cancel Order Programmatically: 3 Simple Ways

by Juvia

Are you looking for Magento 2 Cancel Order Programmatically, this article is for you.

This guide provides you how to cancel order by coding in Magento 2, and another simple way to cancel purchase.

Step by Step Magento 2 Cancel Order Programmatically

To Magento 2 cancel order programmatically, you need to follow the 3 steps below.

Step 1: To make change, go to the path: app/code/VENDOR/EXTENSION/Controller/Adminhtml/Order/Cancel.php

Then, add the following code:

namespace VENDOR\EXTENSION\Controller\Adminhtml\Order;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Sales\Controller\Adminhtml\Order\Cancel as CancelOrderController;
class Cancel extends CancelOrderController implements HttpGetActionInterface
{
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $order = $this->_initOrder();
        if ($order)
        {
            try
            {
                $this->orderManagement->cancel($order->getEntityId());
                $this->messageManager->addSuccessMessage(__('You canceled the order.'));
            } 
            catch (\Magento\Framework\Exception\LocalizedException $e)
            {
                $this->messageManager->addErrorMessage($e->getMessage());
            }
            catch (\Exception $e)
            {
                $this->messageManager->addErrorMessage(__('You have not canceled the item.'));
                $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
            }
        }
        return $resultRedirect->setPath('sales/order/index');
    }
}

Step 2: Modify sales_order_grid.xml

Navigate to app/code/VENDOR/EXTENSION/view/adminhtml/ui_component/sales_order_grid.xml and add the following code:

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <columns name="sales_order_columns">
        <actionsColumn name="actions" class="VENDOR\EXTENSION\UI\Component\Listing\Column\Actions"/>
    </columns>
</listing>

Step 3: Create Actions.php

Navigate to the following path:

app/code/VENDOR/EXTENSION/UI/Component/Listing/Column/Actions.php

And add the below code:

namespace VENDOR\EXTENSION\UI\Component\Listing\Column;
use Magento\Sales\Ui\Component\Listing\Column\ViewAction;
class Actions extends ViewAction
{
    public function prepareDataSource(array $dataSource)
    {
        $dataSource =  parent::prepareDataSource($dataSource);
        if (isset($dataSource['data']['items']))
        {
            foreach ($dataSource['data']['items'] as & $item)
            {
                if (isset($item['entity_id']))
                {
                    $urlEntityParamName = $this->getData('config/urlEntityParamName') ?: 'entity_id';
                    $item[$this->getData('name')]['cancel'] =
                        [
                            'href' => $this->urlBuilder->getUrl(
                                'cancel/order/cancel',
                                [
                                    $urlEntityParamName => $item['entity_id']
                                ]
                            ),
                            'label' => __('Cancel')
                        ];
                }
            }
        }
        return $dataSource;
    }
}

Step 4: Update routes.xml

Navigate to app/code/VENDOR/EXTENSION/etc/adminhtml/routes.xml and add the following code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="cancel" frontName="cancel">
            <module name="VENDOR_EXTENSION" before="Magento_Sales" />
        </route>
    </router>
</config>

These steps collectively allow you to add a “Cancel” action in the Magento admin panel for order items.

The Simple Way to Cancel Magento 2 Orders Without Coding

magento_2_frontend_cancel_order

In regular Magento stores, canceling orders usually requires coding skills because it’s not a built-in feature. However, there’s a handy solution called Magento 2 Cancel Order Frontend. This tool makes it easy for customers to cancel their orders directly on the website. Also, store admins can set it up to automatically cancel pending orders after a specific time, making the process smoother without needing to write complicated code.

With this module, you can easily perform Magento cancel order programmatically.

In Fronted

Our extension allows your customers to cancel their orders from the frontend.

Step 1: To cancel orders, they need to login, then go to My Account ⇒ Account Dashboard or My Orders. The recent orders is displayed. The customers can see the status of their order in this table, click Cancel Oder to cancel this purchase. Noted that Cancel Order can only apply to pending products.

magento-2-cancel-order-programmatically

Step 2: After click Cancel Order, there will be a confirmation popup which allows them to enter comments.

  • Yes: The order will be cancelled
  • No: The order won’t be cancelled

confirmation-popup

After you choose Yes, an email confirmation will be sent to admins automatically, order status will be changed from Pending to Canceled, and auto restock products.

 auto-restock-products

In Backend

To set up for your customers to perform easy actions in the frontend, the admin must configs this module in the backend according to the steps below.

Step 1: Go through System ⇒ Configuration ⇒ BSS Commerce ⇒ Cancel Order

Step 2: In Cancel Order Config Setting, set up the items below to activate the module

Cancel-Order-Config-Setting

Step 3: To set up the automation email to notification cancel orders, go to Marketing ⇒ Communications ⇒ Email Templates ⇒ Add New Template

set-up-the-automation-email

Fill in the content and necessary information of the email to complete the setup.

Fill-content

Furthermore, let’s read other useful articles related to Magento Order from our team below:

Conclusion

Above are detailed instructions for Magento 2 cancel order programmatically. Hopefully, through this guide, everyone can cancel their order easily. Besides, don’t forget that our Magento 2 Frontend Cancel Order is always ready for you without tech knowledge.

BSS Commerce is one of the leading Magento 2 module providers and Magento development agencies in the world. With more than 11 years of working experience, we commit to revolutionizing your eCommerce business with top-class solutions. Don’t hesitate to reach out to us if you have any requests, our experts are happy to support!

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.