We just need to pass order id in generateInvoice($orderId) function from template. Below code snippet is used for generating Invoice in Magento 2, After generating an invoice automatically send the invoice mail to a customer who has placed the order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | <?php namespace Rbj\Invoice\Block; class Invoice extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, \Magento\Sales\Model\Service\InvoiceService $invoiceService, \Magento\Framework\DB\TransactionFactory $transactionFactory, \Magento\Framework\Message\ManagerInterface $messageManager, \Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender, array $data = [] ) { $this->orderRepository = $orderRepository; $this->invoiceService = $invoiceService; $this->transactionFactory = $transactionFactory; $this->messageManager = $messageManager; $this->invoiceSender = $invoiceSender; parent::__construct($context, $data); } /** * Create Invoice Based on Order Object * @param \Magento\Sales\Model\Order $order * @return $this */ public function generateInvoice($orderId){ try { $order = $this->orderRepository->get($orderId); if (!$order->getId()) { throw new \Magento\Framework\Exception\LocalizedException(__('The order no longer exists.')); } if(!$order->canInvoice()) { throw new \Magento\Framework\Exception\LocalizedException( __('The order does not allow an invoice to be created.') ); } $invoice = $this->invoiceService->prepareInvoice($order); if (!$invoice) { throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t save the invoice right now.')); } if (!$invoice->getTotalQty()) { throw new \Magento\Framework\Exception\LocalizedException( __('You can\'t create an invoice without products.') ); } $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE); $invoice->register(); $invoice->getOrder()->setCustomerNoteNotify(false); $invoice->getOrder()->setIsInProcess(true); $order->addStatusHistoryComment('Automatically INVOICED', false); $transactionSave = $this->transactionFactory->create()->addObject($invoice)->addObject($invoice->getOrder()); $transactionSave->save(); // send invoice emails, If you want to stop mail disable below try/catch code try { $this->invoiceSender->send($invoice); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t send the invoice email right now.')); } } catch (\Exception $e) { $this->messageManager->addError($e->getMessage()); } return $invoice; } |
Call function from a template,
1 2 | $orderId = 1; $block->generateInvoice($orderId); |
Hi Rakesh,
Thank you for sharing such a knowledgeable blog and programme code.
Thank you