How To

How to Add Custom Fields in Invoice Totals in Magento 2 Invoice Email Programmatically?

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.

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

<?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

<?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!

Click to rate this post!
[Total: 3 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

6 days ago