Magento 2 – Extending Order Email Template

magento-2.1.3order-emailsales-order

I am trying to extend the Order Confirmation Email Template to add the custom attribute. When I am trying to add code to core class it's printing the value in the email template. When enabling to my extended module it's not printing the value.

For this, I have done code.

di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Sales\Model\Order\Email\Sender\OrderSender" type="ABCSolutions\SalesEmail\Model\Order\Email\Sender\OrderSender" />
</config>

OrderSender.php

/**
     * Prepare email template with variables
     *
     * @param Order $order
     * @return void
     */
    protected function prepareTemplate(Order $order)
    {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customer = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface')->getById($order->getCustomerId());

        /** @param string $abccustomattribute*/
        $abccustomattribute = null;

        $customAttributes = $customer->getCustomAttributes();
        if(isset($customAttributes['abccustomattribute'])){
            $abccustomattributecode= $customAttributes['abccustomattribute'];
            if($abccustomattributecode->getAttributecode() == "abccustomattribute"){
                $abccustomattribute= $abccustomattributecode->getValue();
                $abccustomattribute.= " Working";
            }
        }

        file_put_contents('Order1.txt', print_r("\n" . 'API: ' . $abccustomattribute,true), FILE_APPEND);

        $transport = [
            'order' => $order,
            'billing' => $order->getBillingAddress(),
            'payment_html' => $this->getPaymentHtml($order),
            'store' => $order->getStore(),
            'formattedShippingAddress' => $this->getFormattedShippingAddress($order),
            'formattedBillingAddress' => $this->getFormattedBillingAddress($order),
            'abccustomattribute' => $abccustomattribute
        ];

        $transport = new \Magento\Framework\DataObject($transport);

        $this->eventManager->dispatch(
            'email_order_set_template_vars_before',
            ['sender' => $this, 'transport' => $transport]
        );

        $this->templateContainer->setTemplateVars($transport->getData());

        parent::prepareTemplate($order);
    }

After I have added the {{var abccustomattribute}} variable to Order Email template file order_new.html file.

Could you please suggest me where I went wrong?

Best Answer

You can try the following code to add Custom data in the email template.
app/code/Anshu/Emails/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Anshu_Emails',
    __DIR__
);

app/code/Anshu/Emails/etc/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="Anshu_Emails" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

app/code/Anshu/Emails/etc/events.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <event name="email_order_set_template_vars_before">
        <observer name="anshu_emails_variable_order" instance="Anshu\Emails\Observer\AddMyData" />
    </event>
</config>

app/code/Anshu/Emails/Observer/AddMyData.php

<?php

namespace Anshu\Emails\Observer;

use Magento\Framework\Event\ObserverInterface;

class AddMyData implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $transport = $observer->getTransport();
        $transport['myvar'] = 'My Value';
        if ($transport['payment_html'] == 'transfer') {
            $transport['payment_html'] = 'myvar';
        }
    }
}


Now you can call a new data variable as {{var myvar|raw}} in the new order email template. You can create a new template from Marketing -> Email Templates -> Add New Template

Related Topic