1

I want to create an observer that will execute some code when a new product is added. However, it seems that catalog_product_save_before, catalog_product_save_after and catalog_product_save_commit_after will all fire when an existing product is being saved. Is there an event that will fire exclusively for new products or alternatively a way to differentiate between an existing product being saved and a new one being created with the previously mentioned events?

1

You should be able to rely on $product->isObjectNew(), this gets set in _beforeSave before the event catalog_product_save_before is triggered. It essentially performs a check on whether $product->getId() has a value before save is called and persists that value for the life of the object within that request.

  • Thank you for your fast answer. This works fine for catalog_product_save_before but doesn't persist for the other events. Is this the only event where you can differentiate or can it be done with the others too? – browndesk965 Jan 30 '15 at 12:00
  • Whilst I haven't actually tested it, since Mage_Core_Model_Abstract::_beforeSave calls ->isObjectNew(true) which sets a protected property to true before triggering the _save_before event, the _save_after and _save_commit_after events passed the same instance should also return true for $product->isObjectNew(), since this favours the cache variable over ->getId(). – Peter O'Callaghan Jan 30 '15 at 12:25
  • @browndesk965 Did you ever get this to work outside of catalog_product_save_before? isObjectNew() is true in save_before, but not in save_after every time I try. – Tim Ramsey Aug 8 '17 at 13:42
3

For me the isObjectNew() was available in catalog_product_save_before, but was not available in catalog_product_save_after. I simply created my own isNew variable in the Observer and set it to true in beforeSave and checked it in the afterSave methods.

<?php
class Some_Module_Model_Observer
{
    protected $isNew = false;
    public function beforeSave($observer)
    {
        $product = $observer->getEvent()->getProduct();
        if ($product->isObjectNew()) {
            $this->isNew = true;
        }
    }

    public function afterSave($observer)
    {
        $product = $observer->getEvent()->getProduct();
        if ($this->isNew) {
            /*Add Logic Here*/
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.