0

I have a custom admin grid module. When I add an item to that grid it calls the saveAction() in the controller of my module (obviously).

I need to trigger a custom event after the record gets saved (like shown below).

public function saveAction() {
    if ($data = $this->getRequest()->getPost('tendor')) {
    try {
            $tendor = $this->_initTendor();
            $tendor->addData($data);
            $products = $this->getRequest()->getPost('products', -1);
            if ($products != -1) {
                $tendor->setProductsData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($products));
            }
            $tendor->save();
            // custom event to save vendor code
            $evtData = array('tendor_info' => $data, 'tendor_instance' => $tendor);
            Mage::dispatchEvent('my_custom_tendor_save_after', $evtData);

Now I want this event to be triggered only when a new record is added and not when the existing record is edited.

How can I find the difference between creation of record and updation of a record?

can someone help me in figuring this out?

2

You have this line in your controller:

$tendor = $this->_initTendor();

I can only assume that this takes the id parameter from _GET and loads the appropriate entity from the db. You can add this line right below the line I mentioned:

$shouldDispatchEvent = !(bool)($tendor->getId());

$shouldDispatchEvent is true only if the $tendor object has an id.
Now wrap your dispatchEvent in this:

if ($shouldDispatchEvent){
    $evtData = array('tendor_info' => $data, 'tendor_instance' => $tendor);
    Mage::dispatchEvent('my_custom_tendor_save_after', $evtData);
}

[EDIT].
An other way of doing it, in your case could be this:

if ($tendor->isObjectNew()){
    $evtData = array('tendor_info' => $data, 'tendor_instance' => $tendor);
    Mage::dispatchEvent('my_custom_tendor_save_after', $evtData);
}

This will work if your model extends Mage_Core_Model_Abstract (and it should).
the member _isObjectNew is added to the model instance in the _beforeSave (see Mage_Core_Model_Abstract::_beforeSave()) method, and since you want to dispatch your event after the save is done you should be able to access it.

  • 1
    You are too fast for me. I'll stop writing my answer now :-/ – Fabian Blechschmidt Oct 30 '13 at 11:29
  • 1
    @FabianBlechschmidt. I still say you should add it. It will improve the answer ratio for this website and maybe you explain it better. – Marius Oct 30 '13 at 11:35
  • Thumbs Up for isObjectNew() ! – Shathish Oct 30 '13 at 11:37

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.