3

I need to execute some actions when the Order Invoice is created, so I've made an Observer and I've attached it to 'sales_order_invoice_save_after' event.

The problem is that my Observer function is called when the Invoice is made but also when Comments are added to the Invoice.

How could I check for that, so I could execute my actions only when the Invoice is made?

  • 1
    Have you tried calling isObjectNew on the invoice in the observer to determine if it is the first save before executing your logic? Not positive, but I think this should work, so you might give it a shot. – davidalger Mar 10 '15 at 21:27
  • @davidalger I tried the isObjectNew on the $observer->getEvent()->getInvoice() but is false in both cases (creation and comment). – Riccardo Mar 11 '15 at 10:42
  • 1
    You could add a own parameter $invoice->setData('_only_once', true) and the second time check if it is set... Works for me every time – Jeroen Mar 12 '15 at 20:35
3

This is a somewhat older question but I ran into the same situation where I needed this. I came up with what I think is a more elegant solution by comparing the 'created at' and 'updated at' date/time stamps of the invoice. If they are the same it's a new invoice, if they aren't, it's an update.

In code:

$_invoice = $observer->getEvent()->getInvoice();
if ($_invoice->getUpdatedAt() == $_invoice->getCreatedAt()) {

    // Logic for new invoices

} else {

    // Logic for when invoice is updated

}

Hope this helps for other people needing this in the future.

  • I prefer this solution as is seems there is no such event like for orders sales_order_place_after . But I pray that createdAt and updatedAt will never differ for a second and new orders – ahe_borriglione Aug 2 '17 at 9:50
1

This isn't the most elegant of the methods but at least in my environment it works.

I've checked the content of the Event and found that there's a "data_object" with a protected field "$_comment" that is populated when you're adding a comment and empty when creating the invoice.

So I've made a check on $observer->getEvent()->getDataObject()->getCommentsCollection()->getItems() to control if execute my functions or not.

0

I had a giant answer on this question, and revised it to just do this:

if ($invoice->wasPayCalled())  {
  // Do stuff for new invoices
} else {
  // Do stuff for changes to existing invoices like comments and stuff.
}

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.