Magento – Determine if Customer is New in customer_save_after Event

customerevent-observerregister

I have events that I wish to execute when a customer registers or saves their details. For this, I am using two events: customer_register_success and customer_save_after. The problem I am having is that I end up running the task twice as customer_save_after is always called in the same execution as customer_register_success.

I have tried to detect whether the customer is new by checking the original data and called isObjectNew, but both return data that implies the object is in fact not new. How can I check to see if the customer is just registering in the customer_save_after event short of setting something in the registry in the customer_register_success event?

Best Answer

First of all you can define your observer as singleton for both events

<global>
    <events>
        <customer_save_after>
            <observers>
                <namespace_module>
                    <type>singleton</type>
                    <class>namespace_module/observer</class>
                    <method>doSomething</method>
                </namespace_module>
            </observers>
        </customer_save_after>
        <customer_register_success>
            <observers>
                <namespace_module>
                    <type>singleton</type>
                    <class>namespace_module/observer</class>
                    <method>doSomething</method>
                </namespace_module>
            </observers>
        </customer_register_success>
    </events>
</global>

In this case the same observer object will be used for both events. So you can create flag in your observer and before doing some actions check it.

class [Namespace]_[Module]_Model_Observer
{
    protected $canDoSomething = false;

    public function doSomething($observer)
    {
        if (!$this->canDoSomething) {

            //here your code

            //now set flag to true to prevent executing your code twice 
            $this->canDoSomething = true;
        }
    }
}

Now your code will be executed only once.

Related Topic