How to trigger an event only on record creation and not on updation?
-
16-10-2019 - |
문제
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?
해결책
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.