Magento 1.x Fatal Error – Call to a Member Function getData() on a Non-Object

magento-1magento-1.6magento-1.7

I am developing a custom module where an xml file will be created after order completion for each order.

I have called a function exportOrder on occuring of an event "sales_order_place_after". Following is the code of my function

public function exportOrder($order){
    $dirPath = Mage::getBaseDir('var').DS.'export';

    //if the export directory does not exist, create it
    if (!is_dir($dirPath)) {
         mkdir($dirPath, 0777, true);
    }

    $data = $order->getData();

    $xml = new SimpleXMLElement('<root/>');
    array_walk_recursive($data, array ($xml, 'addChild'));

    file_put_contents(
        $dirPath.DS.$order->getIncrementId().'.xml',
        $xml->asXML()
    );

Now here on line no 12 ie: $data->getData(); I am getting an error

Fatal error: Call to a member function getData() on a non-object in /home/user_www/aliasgar/magentotesting/app/code/local/Meteorify/Observerexample/Model/Export.php on line 12

My config.xml is as follows

<global>
<helpers>
    <orderexport>
        <class>Meteorify_Observerexample_Helper</class>
    </orderexport>
</helpers>
<models>
    <meteorify_observerexample>
         <class>Meteorify_Observerexample_Model</class>
    </meteorify_observerexample>
</models>
<events>
  <checkout_onepage_controller_success_action>
    <observers>
      <sales_order_place_after>
        <type>singleton</type>
        <class>Meteorify_Observerexample_Model_Observer</class>
        <method>exportOrder</method>
      </sales_order_place_after>
    </observers>
  </checkout_onepage_controller_success_action>     
</events>

This is how my Observer.php file looks

class Meteorify_Observerexample_Model_Observer extends Varien_Object{

public function exportOrder($observer) {
    $order = $observer->getEvent()->getOrder();
    Mage::log($order);
    Mage::getModel('meteorify_observerexample/export')->exportOrder($order);
    return true;
}

}

I am not able to figure out the mistake. Please help me in this

Best Answer

You are using the event incorrectly.

In event checkout_onepage_controller_success_action

the order is not sent as an object, but as the order id. (as order_ids)

Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));

(ref Mage_Checkout_OnepageController::successAction)

Thus in your observer you need to get the id, as such:

$orderIds = $observer->getEvent()->getOrderIds(); // returns an array 
$orderId = array_shift($orderIds);

and instantiate the order object using

$order = mage::getModel('sales/order')->load($orderId);

(the above written off the top of my head, but the jest of it should be correct)

Related Topic