2

I have to override Sender.php which path is Magento\Sales\Model\Order\Email

I try but its not work my code is :

di.xml

<type name="Magento\Sales\Model\Order\Email\Sender">
        <plugin name="module_name::aroundPrepareTemplate" type="module\name\Model\Order\Email\Sender" sortOrder="99999"/>
    </type>

module\name\Model\Order\Email Sender.php

<?php  

    namespace module\name\Model\Order\Email;

    use Magento\Sales\Model\Order;
    use Magento\Sales\Model\Order\Email\Container\IdentityInterface;
    use Magento\Sales\Model\Order\Email\Container\Template;
    use Magento\Sales\Model\Order\Address\Renderer;


    abstract class Sender
    {

        protected $senderBuilderFactory;


        protected $templateContainer;


        protected $identityContainer;

        protected $logger;


        protected $addressRenderer;


        public function __construct(
        Template $templateContainer,
        IdentityInterface $identityContainer,
        \Magento\Sales\Model\Order\Email\SenderBuilderFactory $senderBuilderFactory,
        \Psr\Log\LoggerInterface $logger,
        Renderer $addressRenderer
        ) {
            $this->templateContainer = $templateContainer;
            $this->identityContainer = $identityContainer;
            $this->senderBuilderFactory = $senderBuilderFactory;
            $this->logger = $logger;
            $this->addressRenderer = $addressRenderer;
        }


        public function aroundPrepareTemplate($subject,Order $order)
        {
            $this->templateContainer->setTemplateOptions($this->getTemplateOptions());
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $orderItems = $order->getAllItems();

            foreach ($orderItems as $item) {

                $product = $objectManager->get('Magento\Catalog\Model\Product')->load($item->getProductId());
                $categoryIds = $product->getCategoryIds();

            }
            foreach($categoryIds as $catid){
                $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $category = $_objectManager->create('Magento\Catalog\Model\Category')
                ->load($catid);
            }


            if ($order->getCustomerIsGuest()) {
                $templateId = $this->identityContainer->getGuestTemplateId();
                $customerName = $order->getBillingAddress()->getName();
                } else {
                $templateId = $this->identityContainer->getTemplateId();
                $customerName = $order->getCustomerName();
            }

            if($catid == 461){ 
                $templateId = 11 ; 
            }


            $this->identityContainer->setCustomerName($customerName);
            $this->identityContainer->setCustomerEmail($order->getCustomerEmail());
            $this->templateContainer->setTemplateId($templateId);
        }


    }
  • I would say that is impossible. We need to override or plugin its instances. – Khoa TruongDinh May 30 '19 at 11:53
  • How Can I do it? – Krunal Pandya May 30 '19 at 11:54
  • why you define your class as abstract class? – Amit Bera May 30 '19 at 12:00
  • what is the purpose of this Override? – Amit Bera May 30 '19 at 12:01
  • I want to add custom template selection code – Krunal Pandya May 30 '19 at 12:02
2

For your requirement, I am suggesting not use Plugin and it little complicated at this method and

Plugin doesn't work on PrepareTemplate as this Method is protected

Suggesting to use Class rewrite using <preference></preference>.

di.xml code

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Sales\Model\Order\Email\Sender\OrderSender" type="StackExchange\Magento\Rewrite\OrderSender" />
</config>

Rewrite class StackExchange\Magento\Rewrite\OrderSender.php

And code is below:

<?php
namespace StackExchange\Magento\Rewrite;

use Magento\Sales\Model\Order;
use Magento\Framework\DataObject;

class OrderSender extends \Magento\Sales\Model\Order\Email\Sender\OrderSender{

    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    private $productRepository;

    public function __construct(
            \Magento\Sales\Model\Order\Email\Container\Template $templateContainer, 
            \Magento\Sales\Model\Order\Email\Container\OrderIdentity $identityContainer, 
            \Magento\Sales\Model\Order\Email\SenderBuilderFactory $senderBuilderFactory,
            \Psr\Log\LoggerInterface $logger,
            \Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
            \Magento\Payment\Helper\Data $paymentHelper,
            \Magento\Sales\Model\ResourceModel\Order $orderResource,
            \Magento\Framework\App\Config\ScopeConfigInterface $globalConfig,
            \Magento\Framework\Event\ManagerInterface $eventManager,
            \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     ) {
        parent::__construct($templateContainer, 
                $identityContainer,
                $senderBuilderFactory,
                $logger,
                $addressRenderer,
                $paymentHelper,
                $orderResource,
                $globalConfig,
                $eventManager
                );
                $this->productRepository = $productRepository;
    }
    protected function prepareTemplate(Order $order){

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


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

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

        $this->templateContainer->setTemplateOptions($this->getTemplateOptions());

        if ($order->getCustomerIsGuest()) {
            $templateId = $this->identityContainer->getGuestTemplateId();
            $customerName = $order->getBillingAddress()->getName();
        } else {
            $templateId = $this->identityContainer->getTemplateId();
            $customerName = $order->getCustomerName();
        }
        $changeTemplateFlag = $this->changeOriginalTemplate($order);
        if($changeTemplateFlag){
            $templateId = 15;
        }
        $this->identityContainer->setCustomerName($customerName);
        $this->identityContainer->setCustomerEmail($order->getCustomerEmail());
        $this->templateContainer->setTemplateId($templateId);;
    }
    private function changeOriginalTemplate($order)
    {
        $this->logger->info(__METHOD__);
        $ConditionCategoryId = 4;
        $orderItems = $order->getAllItems();
        $categoryIds= [];
        foreach ($orderItems as $item) {
            try{
               $product = $this->productRepository
                       ->getById($item->getProductId(), false, $order->getStoreId());
            } catch (\Magento\Framework\Exception\NoSuchEntityException $ex) {
                  continue;  
            }
            $categoryIds = array_merge($categoryIds,$product->getCategoryIds());
        }
        $uniqueCategoryIds = array_unique($categoryIds);

        if(in_array($ConditionCategoryId, $categoryIds)){
            return true;
        }
        return false;

    }
}
| improve this answer | |
  • I need to send a different email template on checking the order status as complete.I followed the above steps but its not working for me. Anything i can need to more other that what is mentioned in the above solution – Nisith Aug 28 '19 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.