0

If I observe sales_order_creditmemo_refund event, there’s no entity_id or increment_id data in the passed object. I presume those are added before the sales_order_creditmemo_safe_after event. However, if I use the latter, it fires even if I add comments to a previously saved credit memo.

Is there a way to distinguish whether the event is triggered after a freshly refunded credit memo or anything else, or to get Id from the _refund event?

Checking for a state is not an option as orders can have multiple credit memos.

Thank you!

  • Did you have increment id of order? – Rohan Hapani Apr 22 at 4:14
  • I do have order_id, but orders have no creditmemo collections stored before the _refund event. Like HelgeB pointed out below, objects are only saved to the database shortly before the _save_after event. – Mike Apr 22 at 22:15
2

You will have an entity_id only after the object has been saved to database, therefore the earliest event to get that value is sales_order_creditmemo_safe_after.

But an increment_id can be generated in an earlier phase - you just have to generate it by yourself. Automatically the increment_id is generated in the save bevore process of the ressource model but only if there is no value for increment_id.

So one approach for you requirement can be to create the increment_id in your observer in sales_order_creditmemo_refund like this:

if (!$creditmemo->getIncrementId()){
    $entityType = Mage::getModel('eav/entity_type')->loadByCode('creditmemo');
    $creditmemo->setIncrementId($entityType->fetchNewIncrementId($creditmemo->getStoreId()));
}
//from here you have an increment id
$creditmemo->getIncrementId();

You may also use sales_order_creditmemo_safe_after event and check if an increment_id or an entity_id has just been generated, by checking the getOrigData of the creditmemo. That may also work and you will fire the event only once for the newly generated creditmemo:

if ($creditmemo->getOrigData('increment_id') == null){
  //creditmemo has just been generated and saved to database so you have increment_id and entity_id
  $creditmemo->getId();
  $creditmemo->getIncrementId();
}

You can try both approaches and see which one is the best for you - I would prefer the second varaint since you are sure the creditmemo has been generated and saved to database.

  • The second approach works really well. Greatly appreciated! – Mike Apr 22 at 22:05

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.