Magento: Check if object is new after save – isObjectNew

Tweet about this on TwitterShare on LinkedInShare on Google+Share on FacebookEmail this to someone

In Magento If you have case when you need to check if some object is new ( just created ) in after save callback, in some function where you use $object->save() or somewhere else, you can use next method:

$object->isObjectNew();

This function is available in all Magento CE releases >= 1.4.0.0

Some examples:

In observer:

public function myAfterSaveHandler(Varien_Event_Observer $observer) {
	$object = $observer->getEvent()->getDataObject();
	if($object->isObjectNew()) {
		//do something
	}
}

In save action of some controller:

public function saveAction() {
	...
	$object->save();
	...
	if($object->isObjectNew()) {
		//do something
	}
	...
}

How it works:

In Mage_Core_Model_Abstract we have flag:

    /**
     * Flag which allow detect object state: is it new object (without id) or existing one (with id)
     *
     * @var bool
     */
    protected $_isObjectNew     = null;

and next function, that checks the state of the flag:

    /**
     * Check object state (true - if it is object without id on object just created)
     * This method can help detect if object just created in _afterSave method
     * problem is what in after save object has id and we can't detect what object was
     * created in this transaction
     *
     * @param bool $flag
     * @return bool
     */
    public function isObjectNew($flag=null)
    {
        if ($flag !== null) {
            $this->_isObjectNew = $flag;
        }
        if ($this->_isObjectNew !== null) {
            return $this->_isObjectNew;
        }
        return !(bool)$this->getId();
    } 

The key moment here is in before save callback:

    /**
     * Processing object before save data
     *
     * @return Mage_Core_Model_Abstract
     */
    protected function _beforeSave()
    {
        if (!$this->getId()) {
            $this->isObjectNew(true);
        }
        Mage::dispatchEvent('model_save_before', array('object'=>$this));
        Mage::dispatchEvent($this->_eventPrefix.'_save_before', $this->_getEventData());
        return $this;
    }

As you can see, in _beforeSave(), if the object hasn’t id we set the flag $_isObjectNew to TRUE. My first thought when I tried to check if the object is new was to try to inspect object’s data and origData … values like $object->getData(‘id’) and $object->getOrigData(‘id’)

I suspected, that will have something like empty origData()
… YES …, but NO :)

Some thoughts:

If you read with attention, may be noticed, that the function isObjectNew is public and it allows you to assign value to the flag $_ isObjectNew. We need to pay attention in next situations:

1 ) We set isObjectNew to true in before save handler:

public function myBeforeSaveHandler(Varien_Event_Observer $observer) {
	$object = $observer->getEvent()->getDataObject();
	$object->isObjectNew(true);
} 
public function myAfterSaveHandler(Varien_Event_Observer $observer) {
	$object = $observer->getEvent()->getDataObject();
	if($object->isObjectNew()) {
		//$object->isObjectNew() will return true
		//do something
	}
}

2 ) We set isObjectNew to false in before save handler:

public function myBeforeSaveHandler(Varien_Event_Observer $observer) {
	$object = $observer->getEvent()->getDataObject();
	$object->isObjectNew(false);
} 
public function myAfterSaveHandler(Varien_Event_Observer $observer) {
	$object = $observer->getEvent()->getDataObject();
	if(!$object->isObjectNew()) {
		//$object->isObjectNew() will return false
		//do something
	}
}

It’s good to keep in mind, that we can set isObjectNew(false) in some before save handler, but it depends of the logic of your custom extension.

So, that’s my thought about isObjectNew function. Do you have any?

Will be happy if this article will help to somebody!

Tweet about this on TwitterShare on LinkedInShare on Google+Share on FacebookEmail this to someone

Tsvetan Stoychev

Tsvetan aka. Cecko is the founder of Cecko's Lab. He is Magento addicted since Magento CE 1.2.1.2 and has worked on over 30 Magento projects. At the moment he is in charge to take care about the money flow of the company, to keep constant communication with the clients and to keep the people in the office busy.

More Posts

Follow Me:
TwitterLinkedIn

  • Anonymous

    @2091886e55e6b8afea2dffbe0c969b5e:disqus Nice catch! I played with customer model and found the reason why it doesn’t work. Take a look at Mage_Eav_Model_Entity_Abstract at the last lines of protected function _processSaveData we change the flag to false: $newObject->isObjectNew(false); I also found, that when you you save customer for first time the orig data is empty, so you can inspect orig data. I not sure if inspecting the orig data is the best way yo do it. I don’t know where exactly do you need to check if the customer is new, but check if “customer_register_success” event works for you.

  • I noticed this event too. Right now it fires multiple times and doesn’t like isObjectNew.

  • ceckoslab

    Hi @twitter-14536890:disqus 😉 I guess, that the Customer Model is saved multiple times in a single request and that’s why your event handler is called multiple times. You can deal with the multiple calls of your event handler by using the idea of Branko Ajzele in this post: http://inchoo.net/ecommerce/magento/custom-magento-events-customer-first-order/ … check the last code snippet. Branko uses a variable “private static $_handleCustomerFirstOrderCounter = 1;” and later he increments this variable. This helps him to detect the first call of his event handler. 

  • Magento Developer

    $customer->isObjectNew() not working in event: customer_save_commit_after but works in customer_save_before, any idea?