Magento - customer_save_after always fired twice

David picture David · Apr 30, 2011 · Viewed 9k times · Source

I am using the customer_save_after event in magento, and all is working fine apart from 1 annoying thing - it is always fired twice.

There are no other modules rewriting this and I can find no other reason for this happening. When I look through all of the events getting fired at this time and this event is definately getting fired twice.

Anyone explain this?

I am writing a web service that hooks into this and its turning out to be quite inefficient to duplicate things.

Answer

Jonathan Day picture Jonathan Day · May 20, 2011

I've noticed this double-save behaviour too. The way to prevent issue with your observer is to set a flag in the request that can be checked e.g.

    if(Mage::registry('customer_save_observer_executed')){
        return $this; //this method has already been executed once in this request (see comment below)
    }

    ...execute arbitrary code here....

    /* Customer Addresses seem to call the before_save event twice, 
    * so we need to set a variable so we only process it once, otherwise we get duplicates
    */
    Mage::register('customer_save_observer_executed',true);