4

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?

Riccardo
  • 346
  • 8
  • 16
  • 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
  • 2
    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
  • 1
    @Jeroen your answer saved my day, thanks – yvzyldrm Aug 19 '20 at 14:33

3 Answers3

4

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.

2

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.

Riccardo
  • 346
  • 8
  • 16
1

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.
}
CarComp
  • 1,246
  • 1
  • 15
  • 34