Magento – Magento 2 : Add Custom Field To Order, Invoice, Shipment, Credit Memo

creditmemoinvoicemagento2order-emailshipment

I created one custom field in sales_order table, field name is mycstfield.

I save my value in that field sucessfully when order is placed.

Now, I want to send that field value in following places.

  1. Order Email (From Admin)

enter image description here

  1. Inoive Email and Invoice Print (PDF)

enter image description here

  1. Shipment Print

enter image description here

  1. Credit Memo Email and Credit Memo Print (PDF)

enter image description here

Can Any one have idea about this, How can I do this.

Best Answer

I give my answer about order email. Other emails and pdf should works with the same logic.

You have to look at \vendor\magento\module-sales\view\frontend\layout\sales_email_order_items.xml

where the block with class Magento\Sales\Block\Order\Email\Items has the template \vendor\magento\module-sales\view\frontend\templates\order\items.phtml

In this template the line <?php echo $block->getChildHtml('order_totals') ?> calls the block with totals (always defined in sales_email_order_items.xml)

...
<block class="Magento\Sales\Block\Order\Totals" name="order_totals" template="order/totals.phtml">
...

This template starts with

<?php foreach ($block->getTotals() as $_code => $_total): ?>

where $block is a Magento\Sales\Block\Order\Totals instance.

Then, to add your custom field to totals, try to write a plugin related to one public method of this class, i think you could choose addTotal() or addTotalBefore(), in this way your custom field will be added to $this->_totals array and it will be printed from the foreach loop.

Related Topic