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



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();

    }

}


Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Update Product Stock Programmatically in Magento 2

How to Set and Get Cookie in Magento 2