save order custom field

Morning folks, hope you are well, we had a requirement to set a flag in our enhanced ecommerce module after sending offline data to Google Analytics using measurement protocol. To set this flag we called sales_order_after_save event by adding entry in config.xml

<event> <sales_order_save_after> <observers> <scommerce_universalanalytics_order> <class>scommerce_universalanalytics/observer</class> <method>sendOrderDataToGoogle</method> </scommerce_universalanalytics_order> </observers> </sales_order_save_after>
</events>

then we created observer.php and defined sendOrderDataToGoogle function as mentioned in our config.xml to update the order custom field i.e. sent_data_to_google in sales_flat_order which was created as part of our sql upgrade script as part of sales_order_save_after dispatch event.

/** * Send order data to GA only on order creation * * @return void
*/
public function sendOrderDataToGoogle(Varien_Event_Observer $observer)
{ $objOrder = $observer->getEvent()->getOrder(); if (($order->getStatus() == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT)|| ($order->getStatus() == Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW)) { $objOrder->setSentDataToGoogle(1) ->save(); return; } ......
}

But every time this function was getting called we were getting memory exhausted error and we struggled to figure it out why because it should work without any issue. After several hours of debugging we found out that at this point of time the order is not physical saved in the database and when the save function is performed it goes into infinite loop which causes timeout or exhausting the memory.

We then finally found the solution to fix the problem, we changed the following two lines -:

FROM

$objOrder->setSentDataToGoogle(1) ->save();

TO

$objOrder->setSentDataToGoogle(1);
$objOrder->getResource()->saveAttribute($objOrder, "sent_data_to_google");

And voila, the sent_data_to_google order custom field was saved with value 1 in sales_flat_order table without any more timing out or memory exhausted issue. As it was a painful couple of hours we thought we should share this with our Magento community. Hope it saves someone some effort, happy programming!!!!

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts