Jack
Jack

Reputation: 100

Magento event not triggered when order cancel programmatically

I am running a script to cancel order automatically. My script looks something like this.

$order->cancel()->save();

The problem with this is that, it cancels order correctly but does not seem to dispatch order_cancel_after event.

How should I solve this, can I dispatch this event in my script? Why is this cancel action different from click the cancel button in the backend order page?

Upvotes: 2

Views: 1962

Answers (2)

sdaugherty
sdaugherty

Reputation: 278

Here is what I came up with to get the order_cancel_after event to fire on the frontend when $order->cancel() is called. I had to implement this for a Magento_Authorizenet issue where that event wasn't being fired when credit card's were declined.

Edit: I just realized your question was for Magento 1 EE. I'll leave this here in case anyone is having this issue on Magento 2 EE as well.

Create the following files with the specified content (Replacing [Vendor] with your vendor name):

app/code/[Vendor]/Reward/registration.php

This file is responsible for letting Magento know about your module. After adding all files in this answer, you will need to run php bin/magento setup:upgrade.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '[Vendor]_Reward',
    __DIR__
);

app/code/[Vendor]/Reward/etc/module.xml

This file declares the setup version of the module and any modules it depends on (Magento_Reward in our case).

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="[Vendor]_Reward" setup_version="0.1.0">
        <sequence>
            <module name="Magento_Reward"/>
        </sequence>
    </module>
</config>

app/code/[Vendor]/Reward/etc/frontend/events.xml

This file will register the stock Magento_Reward observer that is already defined for adminhtml (backend), but do it for the frontend (because of it's location in etc/frontend):

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="order_cancel_after">
        <observer name="magento_reward" instance="Magento\Reward\Observer\ReturnRewardPoints" />
    </event>
</config>

Upvotes: 1

Abhishek Dhanraj Shahdeo
Abhishek Dhanraj Shahdeo

Reputation: 1356

You can dispatch your own event like this:

Mage::dispatchEvent(
        'order_cancel_after',
        array('order' => $order, 'quote' => $this->getQuote())
    );

Place this code accroding to your usage.

Upvotes: 0

Related Questions