Magento 1.9 Observer – sales_order_save_after Preventing Order from Saving

checkoutevent-observerextensionsmagento-1.9module

I created a module that changes a customer's group if their order is completed. I'm using magento 1.9.3.1 and my module is causing some problems when checking out as a guest.

In one example, checking out returns an error to the customer saying "Customer email is required". The order email is sent and the payment is processed but the order is not actually saved in the database. The customer is returned the error "Customer email is required" on the checkout page as if the order/payment hasn't gone through.

I've disabled the magestore onestepcheckout/giftcard extensions I'm using and the problem persists. I've disabled my template to confirm that's not related to the issue.

My setup file (app/etc/modules/EXAMPLE_ApproveCustomer.xml)

<?xml version="1.0"?>
<config>
    <modules>
        <EXAMPLE_ApproveCustomer>
            <codePool>local</codePool>
            <active>true</active>
        </EXAMPLE_ApproveCustomer>
    </modules>
</config>

My config file (app/code/local/EXAMPLE/ApproveCustomer/etc/config.xml)

<?xml version="1.0"?>
<config>
    <modules>
        <EXAMPLE_ApproveCustomer>
            <version>1.0.0</version>
        </EXAMPLE_ApproveCustomer>
    </modules>
    <global>
        <events>
            <sales_order_save_after>
                <observers>
                    <EXAMPLE_approvecustomer_model_observer>
                        <type>singleton</type>
                        <class>EXAMPLE_ApproveCustomer_Model_Observer</class>
                        <method>updateCustomers_SalesOrderSaveAfter</method>
                    </EXAMPLE_approvecustomer_model_observer>
                </observers>
            </sales_order_save_after>
        </events>
    </global>
</config>

My observer file (app/code/local/EXAMPLE/ApproveCustomer/Model/Observer.php)

<?php
class EXAMPLE_ApproveCustomer_Model_Observer {
    public function updateCustomers_SalesOrderSaveAfter(Varien_Event_Observer $observer) {
        // set group for approved customers
        $approved_group = 6;

        // load order being updated
        $order = $observer->getOrder();

        // check if order is complete
        if(($order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE) || ($order->getStatus() == "complete")){
            // get customer id
            $customer_id = $order->getCustomerId();

            // get customer
            $customer = Mage::getModel('customer/customer')->load($customer_id);

            // update group
            $customer->setGroupId($approved_group)->save();
        }
    }
}
?>

Best Answer

This will be happen if your store allow guest checkout. So you need to modify your code if customer exist then update their group.

Modify following line

if($customer->getId()) {
    // update group
    $customer->setGroupId($approved_group)->save();
}
Related Topic