Hello Magento Friends,
In today’s tutorial, we will learn about How to Add Custom Fields in Invoice Totals in Magento 2 Invoice Email Programmatically?
An admin sends an invoice to customers when the order is placed. Invoices can be generated in the form of PDFs or sent to customers via email. Automatize the invoice process of your Magento 2 store by installing Magento 2 Auto Invoice & Shipment.
Admin can configure invoice email in Magento 2. The invoice email contains order totals and other information. If you want to show custom fields in invoice totals, follow the steps below.
Contents
Steps to Add Custom Fields in Invoice Totals in Magento 2 Invoice Email Programmatically:
Step 1: In the first step you need to create the sales_order_invoice.xml file at the below file path
app/code/Vendor/Extension/view/frontend/layout/sales_order_invoice.xml
Then add the code as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="invoice_totals"> <block class="Vendor\Extension\Block\CustomFieldinInvoice" name="invoice"/> <action method="setLabel"> <argument name="label" xsi:type="string">Custom Field Name</argument> </action> </referenceBlock> </body> </page> |
Step 2: Now create the CustomFieldinInvoice.php file at the following path
app/code/Vendor/Extension/Block/CustomFieldinInvoice.php
Now add the below code
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 |
<?php namespace Vendor\Extension\Block; use Magento\Framework\View\Element\Template; class CustomFieldinInvoice extends Template { public function __construct( Template\Context $context, array $data = [] ) { parent::__construct($context, $data); $this->setInitialFields(); } public function setInitialFields() { if (!$this->getLabel()) { $this->setLabel(__('Custom Field Name')); } } public function initTotals() { $this->getParentBlock()->addTotal( new \Magento\Framework\DataObject( [ 'code' => 'customfield', 'strong' => $this->getStrong(), 'value' => $this->getOrder()->getCustom(), // extension attribute field 'base_value' => $this->getOrder()->getCustom(), 'label' => __($this->getLabel()), ] ), $this->getAfter() ); return $this; } public function getOrder() { return $this->getParentBlock()->getOrder(); } public function getSource() { return $this->getParentBlock()->getSource(); } } |
Conclusion:
Hence, this way, you can easily add custom fields in invoice totals in Magento 2 invoice email programmatically. If you have any doubts, let me know through the comment box. Share the article with your friends and stay in touch with us.
Happy Coding!