Trigger observer on Magento order status change events

user2402942 picture user2402942 · May 20, 2015 · Viewed 14.8k times · Source

I need to automatically create an invoice on an order once it receives the processing status. Which event should be observed in my extension to achieve this?


I'm trying but this code is not working, what can it be?

.xml in etc/modules

<?xml version="1.0"?>
<config>
<modules>
    <Atwix_Orderhook>
        <active>true</active>
        <codePool>community</codePool>
    </Atwix_Orderhook>
</modules>
</config>

config.xml in app/code/...

<?xml version="1.0"?>
<config>
<modules>
    <Atwix_Orderhook>
        <version>1.0</version>
    </Atwix_Orderhook>
</modules>
<global>
    <models>            
        <orderhook>
            <class>Atwix_Orderhook_Model</class>
        </orderhook>
    </models>
    <events>
        <sales_order_save_after>
            <observers>
                <auto_invoice_order>
                    <type>singleton</type>
                    <class>Atwix_Orderhook_Model_Observer</class>
                    <method>implementOrderStatus</method>
                </auto_invoice_order>
            </observers>
        </sales_order_save_after>
    </events>

</global>
</config>

Oberver.php in app/code/...

<?php
class Atwix_Orderhook_Model_Observer 
{
public function implementOrderStatus($event)
{
    $order = $event->getOrder();

    if ($order == 'processing') {
        if ($order->canInvoice())
            $this->_processOrderStatus($order);
    }
    return $this;
}
                        private function _processOrderStatus($order)
                        {
                            $invoice = $order->prepareInvoice();

                            $invoice->register();
                            Mage::getModel('core/resource_transaction')
                               ->addObject($invoice)
                               ->addObject($invoice->getOrder())
                               ->save();

                            $invoice->sendEmail(false, '');
                            return true;
                        }
}

Answer

fantasticrice picture fantasticrice · May 20, 2015

You can observe sales_order_save_after and then check for the order state you are targeting with something like this:

public function exampleEventHandler(Varien_Event_Observer $observer)
{
    /* @var Mage_Sales_Model_Order $order */
    $order = $observer->getOrder();
    $stateProcessing = $order::STATE_PROCESSING;
    // Only trigger when an order enters processing state.
    if ($order->getState() == $stateProcessing && $order->getOrigData('state') != $stateProcessing) {
        ...
    }
    ...
}