Magento create invoice comment programmatically
In this tutorial I show you how to create invoice comment programmatically. Sometimes it is needed to add invoice comments for invoices from you written module. Invoice comments are printed to pdf invoice, so you can inform a customer about anything.
Magento create invoice comment programmatically
Because we do not want to change core files, we create a new module and use an observer to listen to special events. There are two possible invoice events, but only one is usable for this task:
- sales_order_invoice_save_before
There you can make changes to current invoice object which is saved after this observer method. If you make your changes in sales_order_invoice_save_after and manually save invoice, you will create a endless loop and run out of memory (which i did first). So you define correct observer method in your config.xml file:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <adminhtml> <events> ... <sales_order_invoice_save_before> <observers> <yourmodulename> <class>yourmodulename/observer</class> <method>salesOrderInvoiceSaveBefore</method> </yourmodulename> </observers> </sales_order_invoice_save_before> </events> </adminhtml> |
Observer
Your observer should be changed like this (add following method):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public function salesOrderInvoiceSaveBefore(Varien_Event_Observer $observer) { $invoice = $observer->getEvent()->getInvoice(); //coupon message $comments = $invoice->getCommentsCollection(); if($comments->getSize() == 0) { $order = $invoice->getOrder(); $discount_amount = abs($order->getDiscountAmount()); if ($discount_amount > 0 && $order->getCouponCode() && $order->getCouponRuleName() == "generated coupon code" ) { $comment = "A generated coupon code was added with discount amount of ".$discount_amount." EUR."; $invoice->addComment($comment, false/*notify customer*/, true/*visibleOnFront*/); $invoice->_hasDataChanges = true; } } } |
In our shop orders are done normal in frontend or they are imported and created programmatically from an external source. It is possible, that these orders have a coupon code discount added. For this there should be a invoice comment.
In observer method salesOrderInvoiceSaveBefore we can get invoice object easy. Then we check if this order does not have already a comment (just for sure). Next we check if there is a discount for this order if yes, we also check if it uses a coupon code and if this fits a special rule name. If all that is true we simply add a invoice comment with addComment() method. It expects a comment text and two flags. If user should be notified and if it should be visible on frontend.
Conclusion
It is quite easy to create an invoice comment programmatically. This comment is then shown on every PDF invoice and has useful information for a customer.