How to get Creditmemo ID from sales_order_creditmemo_refund?
-
27-02-2021 - |
سؤال
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!
المحلول
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.