How To

How to cancel order Programmatically without disabling URL security key in Magento 2?

Hello Magento Friends 👋,

How are you doing? Today I am going to explain How to cancel order Programmatically without disabling URL security key in Magento 2?. In case you missed out on the previously published blog, it is right here. Magento 2: How To Display Count Of Product with Page Title on Category Page.

Whenever the admin tries to cancel an order from the controller using order ID, it is required to disable the URL security key from Magento 2 admin configuration. Thereby, I am here with the code to cancel order programmatically without disabling  URL security key in Magento 2. Let’s get started 🚀

Steps to cancel order Programmatically without disabling URL security key in Magento 2:

Step 1: Navigate to the following path:

app/code/VENDOR/EXTENSION/Controller/Adminhtml/Order/Cancel.php

And add the below 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: Now, move to the following path:

app/code/VENDOR/EXTENSION/view/adminhtml/ui_component/sales_order_grid.xml

Now, add the below 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: Next, 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: Lastly, navigate to the following path:

app/code/VENDOR/EXTENSION/etc/adminhtml/routes.xml

Finally, add the below 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>

That’s it!

Conclusion:

Hence, hopefully, everyone is able to cancel order Programmatically without disabling URL security key in Magento 2. If you face any hardship while executing the code, kindly mention in the comment section below. Also, share the article with your Magento developer friends. Stay connected!

Happy Coding 😊

Click to rate this post!
[Total: 3 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago