Orders – Observer on sales_order_invoice_save_after Event

event-observerinvoiceorders

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?

Best Answer

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.