How to Add Custom Field in Invoice Totals in Magento 2 Invoice Email Programmatically

Method to Add Custom Field in Invoice Totals in Magento 2 Invoice Email

Create registration.php

Directory

app\code\VendorName\ModuleName\registration.php

Content of registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'VendorName_ModuleName', __DIR__
);

Create module.xml

Directory

app\code\VendorName\ModuleName\etc\module.xml

Content of module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="VendorName_ModuleName" setup_version="1.0.0"/>
</config>

Create sales_order_invoice.xml

Directory

app\code\VendorName\ModuleName\view\frontend\layout\sales_order_invoice.xml

Content of sales_order_invoice.xml

<?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="VendorName\ModuleName\Block\CustomField" name="invoice"/>
<action method="setLabel">
<argument name="label" xsi:type="string">Custom Field Name</argument>
</action>
</referenceBlock>
</body>
</page>

Create CustomField.php

Directory

app\code\Vendor\Module\Block\CustomField.php 

Content of CustomField.php

<?php
namespace VendorName\ModuleName\Block;
use Magento\Framework\View\Element\Template;
class CustomField 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' => 'custom',
'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();
}
}

 

We are providing the best Magento 2 Extentions at the lowest prices.
Related Products