Override abstract classUnit Test for overwrite collection class in magento2Send Copy of Order Confirmation email programmatically in magento 2main.CRITICAL: Plugin class doesn't existMagento 2: How to override newsletter Subscriber modelOverride new order email in magento 2Magento 2.2.5: Overriding Admin Controller sales/orderMonolog Error After 2.2 UpgradeI am trying to override multishipping.php file in vendor/magento/module-multishipping/Model/Checkout/Type/Multishipping.phpIs it possible to add custom shipping address in order email templates in custom module OrderSender.phpIncompatible argument type: Required type: MagentoFrameworkStdlibStringUtils

How to hide an urban landmark?

Determining fair price for profitable mobile app business

Why VGA framebuffer was limited to 64kB window?

Is counterpoint still used today?

What's up with this leaf?

Winning Strategy for the Magician and his Apprentice

How can electric fields be used to detect cracks in metals?

What language is software running on the ISS written in?

Are there downsides to using std::string as a buffer?

What makes Ada the language of choice for the ISS's safety-critical systems?

Taxi Services at Didcot

Do simulator games use a realistic trajectory to get into orbit?

Does Disney no longer produce hand-drawn cartoon films?

Existence of a pointwise convergent subsequence

Using "subway" as name for London Underground?

Medieval flying castle propulsion

SOQL Not Recognizing Field?

Pre-1972 sci-fi short story or novel: alien(?) tunnel where people try new moves and get destroyed if they're not the correct ones

Overlapping String-Blocks

Logarithm of exponential

How to tell your grandparent to not come to fetch you with their car?

Prime Sieve and brute force

Does the spell Clone require any material components to cast on a Zealot barbarian?

Where Mongol herds graze



Override abstract class


Unit Test for overwrite collection class in magento2Send Copy of Order Confirmation email programmatically in magento 2main.CRITICAL: Plugin class doesn't existMagento 2: How to override newsletter Subscriber modelOverride new order email in magento 2Magento 2.2.5: Overriding Admin Controller sales/orderMonolog Error After 2.2 UpgradeI am trying to override multishipping.php file in vendor/magento/module-multishipping/Model/Checkout/Type/Multishipping.phpIs it possible to add custom shipping address in order email templates in custom module OrderSender.phpIncompatible argument type: Required type: MagentoFrameworkStdlibStringUtils






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have to override Sender.php which path is MagentoSalesModelOrderEmail



I try but its not work my code is :



di.xml



<type name="MagentoSalesModelOrderEmailSender">
<plugin name="module_name::aroundPrepareTemplate" type="modulenameModelOrderEmailSender" sortOrder="99999"/>
</type>


modulenameModelOrderEmail
Sender.php



<?php 

namespace modulenameModelOrderEmail;

use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailContainerIdentityInterface;
use MagentoSalesModelOrderEmailContainerTemplate;
use MagentoSalesModelOrderAddressRenderer;


abstract class Sender


protected $senderBuilderFactory;


protected $templateContainer;


protected $identityContainer;

protected $logger;


protected $addressRenderer;


public function __construct(
Template $templateContainer,
IdentityInterface $identityContainer,
MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
PsrLogLoggerInterface $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 = MagentoFrameworkAppObjectManager::getInstance();
$orderItems = $order->getAllItems();

foreach ($orderItems as $item)

$product = $objectManager->get('MagentoCatalogModelProduct')->load($item->getProductId());
$categoryIds = $product->getCategoryIds();


foreach($categoryIds as $catid)
$_objectManager = MagentoFrameworkAppObjectManager::getInstance();
$category = $_objectManager->create('MagentoCatalogModelCategory')
->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);













share|improve this question






















  • I would say that is impossible. We need to override or plugin its instances.

    – Khoa TruongDinh
    May 30 at 11:53











  • How Can I do it?

    – Krunal Pandya
    May 30 at 11:54











  • why you define your class as abstract class?

    – Amit Bera
    May 30 at 12:00











  • what is the purpose of this Override?

    – Amit Bera
    May 30 at 12:01











  • I want to add custom template selection code

    – Krunal Pandya
    May 30 at 12:02

















2















I have to override Sender.php which path is MagentoSalesModelOrderEmail



I try but its not work my code is :



di.xml



<type name="MagentoSalesModelOrderEmailSender">
<plugin name="module_name::aroundPrepareTemplate" type="modulenameModelOrderEmailSender" sortOrder="99999"/>
</type>


modulenameModelOrderEmail
Sender.php



<?php 

namespace modulenameModelOrderEmail;

use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailContainerIdentityInterface;
use MagentoSalesModelOrderEmailContainerTemplate;
use MagentoSalesModelOrderAddressRenderer;


abstract class Sender


protected $senderBuilderFactory;


protected $templateContainer;


protected $identityContainer;

protected $logger;


protected $addressRenderer;


public function __construct(
Template $templateContainer,
IdentityInterface $identityContainer,
MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
PsrLogLoggerInterface $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 = MagentoFrameworkAppObjectManager::getInstance();
$orderItems = $order->getAllItems();

foreach ($orderItems as $item)

$product = $objectManager->get('MagentoCatalogModelProduct')->load($item->getProductId());
$categoryIds = $product->getCategoryIds();


foreach($categoryIds as $catid)
$_objectManager = MagentoFrameworkAppObjectManager::getInstance();
$category = $_objectManager->create('MagentoCatalogModelCategory')
->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);













share|improve this question






















  • I would say that is impossible. We need to override or plugin its instances.

    – Khoa TruongDinh
    May 30 at 11:53











  • How Can I do it?

    – Krunal Pandya
    May 30 at 11:54











  • why you define your class as abstract class?

    – Amit Bera
    May 30 at 12:00











  • what is the purpose of this Override?

    – Amit Bera
    May 30 at 12:01











  • I want to add custom template selection code

    – Krunal Pandya
    May 30 at 12:02













2












2








2








I have to override Sender.php which path is MagentoSalesModelOrderEmail



I try but its not work my code is :



di.xml



<type name="MagentoSalesModelOrderEmailSender">
<plugin name="module_name::aroundPrepareTemplate" type="modulenameModelOrderEmailSender" sortOrder="99999"/>
</type>


modulenameModelOrderEmail
Sender.php



<?php 

namespace modulenameModelOrderEmail;

use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailContainerIdentityInterface;
use MagentoSalesModelOrderEmailContainerTemplate;
use MagentoSalesModelOrderAddressRenderer;


abstract class Sender


protected $senderBuilderFactory;


protected $templateContainer;


protected $identityContainer;

protected $logger;


protected $addressRenderer;


public function __construct(
Template $templateContainer,
IdentityInterface $identityContainer,
MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
PsrLogLoggerInterface $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 = MagentoFrameworkAppObjectManager::getInstance();
$orderItems = $order->getAllItems();

foreach ($orderItems as $item)

$product = $objectManager->get('MagentoCatalogModelProduct')->load($item->getProductId());
$categoryIds = $product->getCategoryIds();


foreach($categoryIds as $catid)
$_objectManager = MagentoFrameworkAppObjectManager::getInstance();
$category = $_objectManager->create('MagentoCatalogModelCategory')
->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);













share|improve this question














I have to override Sender.php which path is MagentoSalesModelOrderEmail



I try but its not work my code is :



di.xml



<type name="MagentoSalesModelOrderEmailSender">
<plugin name="module_name::aroundPrepareTemplate" type="modulenameModelOrderEmailSender" sortOrder="99999"/>
</type>


modulenameModelOrderEmail
Sender.php



<?php 

namespace modulenameModelOrderEmail;

use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailContainerIdentityInterface;
use MagentoSalesModelOrderEmailContainerTemplate;
use MagentoSalesModelOrderAddressRenderer;


abstract class Sender


protected $senderBuilderFactory;


protected $templateContainer;


protected $identityContainer;

protected $logger;


protected $addressRenderer;


public function __construct(
Template $templateContainer,
IdentityInterface $identityContainer,
MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
PsrLogLoggerInterface $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 = MagentoFrameworkAppObjectManager::getInstance();
$orderItems = $order->getAllItems();

foreach ($orderItems as $item)

$product = $objectManager->get('MagentoCatalogModelProduct')->load($item->getProductId());
$categoryIds = $product->getCategoryIds();


foreach($categoryIds as $catid)
$_objectManager = MagentoFrameworkAppObjectManager::getInstance();
$category = $_objectManager->create('MagentoCatalogModelCategory')
->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);










magento2 overrides abstract-class






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 30 at 11:40









Krunal PandyaKrunal Pandya

738




738












  • I would say that is impossible. We need to override or plugin its instances.

    – Khoa TruongDinh
    May 30 at 11:53











  • How Can I do it?

    – Krunal Pandya
    May 30 at 11:54











  • why you define your class as abstract class?

    – Amit Bera
    May 30 at 12:00











  • what is the purpose of this Override?

    – Amit Bera
    May 30 at 12:01











  • I want to add custom template selection code

    – Krunal Pandya
    May 30 at 12:02

















  • I would say that is impossible. We need to override or plugin its instances.

    – Khoa TruongDinh
    May 30 at 11:53











  • How Can I do it?

    – Krunal Pandya
    May 30 at 11:54











  • why you define your class as abstract class?

    – Amit Bera
    May 30 at 12:00











  • what is the purpose of this Override?

    – Amit Bera
    May 30 at 12:01











  • I want to add custom template selection code

    – Krunal Pandya
    May 30 at 12:02
















I would say that is impossible. We need to override or plugin its instances.

– Khoa TruongDinh
May 30 at 11:53





I would say that is impossible. We need to override or plugin its instances.

– Khoa TruongDinh
May 30 at 11:53













How Can I do it?

– Krunal Pandya
May 30 at 11:54





How Can I do it?

– Krunal Pandya
May 30 at 11:54













why you define your class as abstract class?

– Amit Bera
May 30 at 12:00





why you define your class as abstract class?

– Amit Bera
May 30 at 12:00













what is the purpose of this Override?

– Amit Bera
May 30 at 12:01





what is the purpose of this Override?

– Amit Bera
May 30 at 12:01













I want to add custom template selection code

– Krunal Pandya
May 30 at 12:02





I want to add custom template selection code

– Krunal Pandya
May 30 at 12:02










1 Answer
1






active

oldest

votes


















1














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="MagentoSalesModelOrderEmailSenderOrderSender" type="StackExchangeMagentoRewriteOrderSender" />
</config>


Rewrite class StackExchangeMagentoRewriteOrderSender.php



And code is below:



<?php
namespace StackExchangeMagentoRewrite;

use MagentoSalesModelOrder;
use MagentoFrameworkDataObject;

class OrderSender extends MagentoSalesModelOrderEmailSenderOrderSender

/**
* @var MagentoCatalogApiProductRepositoryInterface
*/
private $productRepository;

public function __construct(
MagentoSalesModelOrderEmailContainerTemplate $templateContainer,
MagentoSalesModelOrderEmailContainerOrderIdentity $identityContainer,
MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
PsrLogLoggerInterface $logger,
MagentoSalesModelOrderAddressRenderer $addressRenderer,
MagentoPaymentHelperData $paymentHelper,
MagentoSalesModelResourceModelOrder $orderResource,
MagentoFrameworkAppConfigScopeConfigInterface $globalConfig,
MagentoFrameworkEventManagerInterface $eventManager,
MagentoCatalogApiProductRepositoryInterface $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 (MagentoFrameworkExceptionNoSuchEntityException $ex)
continue;

$categoryIds = array_merge($categoryIds,$product->getCategoryIds());

$uniqueCategoryIds = array_unique($categoryIds);

if(in_array($ConditionCategoryId, $categoryIds))
return true;

return false;








share|improve this answer























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f276726%2foverride-abstract-class%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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="MagentoSalesModelOrderEmailSenderOrderSender" type="StackExchangeMagentoRewriteOrderSender" />
    </config>


    Rewrite class StackExchangeMagentoRewriteOrderSender.php



    And code is below:



    <?php
    namespace StackExchangeMagentoRewrite;

    use MagentoSalesModelOrder;
    use MagentoFrameworkDataObject;

    class OrderSender extends MagentoSalesModelOrderEmailSenderOrderSender

    /**
    * @var MagentoCatalogApiProductRepositoryInterface
    */
    private $productRepository;

    public function __construct(
    MagentoSalesModelOrderEmailContainerTemplate $templateContainer,
    MagentoSalesModelOrderEmailContainerOrderIdentity $identityContainer,
    MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
    PsrLogLoggerInterface $logger,
    MagentoSalesModelOrderAddressRenderer $addressRenderer,
    MagentoPaymentHelperData $paymentHelper,
    MagentoSalesModelResourceModelOrder $orderResource,
    MagentoFrameworkAppConfigScopeConfigInterface $globalConfig,
    MagentoFrameworkEventManagerInterface $eventManager,
    MagentoCatalogApiProductRepositoryInterface $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 (MagentoFrameworkExceptionNoSuchEntityException $ex)
    continue;

    $categoryIds = array_merge($categoryIds,$product->getCategoryIds());

    $uniqueCategoryIds = array_unique($categoryIds);

    if(in_array($ConditionCategoryId, $categoryIds))
    return true;

    return false;








    share|improve this answer



























      1














      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="MagentoSalesModelOrderEmailSenderOrderSender" type="StackExchangeMagentoRewriteOrderSender" />
      </config>


      Rewrite class StackExchangeMagentoRewriteOrderSender.php



      And code is below:



      <?php
      namespace StackExchangeMagentoRewrite;

      use MagentoSalesModelOrder;
      use MagentoFrameworkDataObject;

      class OrderSender extends MagentoSalesModelOrderEmailSenderOrderSender

      /**
      * @var MagentoCatalogApiProductRepositoryInterface
      */
      private $productRepository;

      public function __construct(
      MagentoSalesModelOrderEmailContainerTemplate $templateContainer,
      MagentoSalesModelOrderEmailContainerOrderIdentity $identityContainer,
      MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
      PsrLogLoggerInterface $logger,
      MagentoSalesModelOrderAddressRenderer $addressRenderer,
      MagentoPaymentHelperData $paymentHelper,
      MagentoSalesModelResourceModelOrder $orderResource,
      MagentoFrameworkAppConfigScopeConfigInterface $globalConfig,
      MagentoFrameworkEventManagerInterface $eventManager,
      MagentoCatalogApiProductRepositoryInterface $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 (MagentoFrameworkExceptionNoSuchEntityException $ex)
      continue;

      $categoryIds = array_merge($categoryIds,$product->getCategoryIds());

      $uniqueCategoryIds = array_unique($categoryIds);

      if(in_array($ConditionCategoryId, $categoryIds))
      return true;

      return false;








      share|improve this answer

























        1












        1








        1







        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="MagentoSalesModelOrderEmailSenderOrderSender" type="StackExchangeMagentoRewriteOrderSender" />
        </config>


        Rewrite class StackExchangeMagentoRewriteOrderSender.php



        And code is below:



        <?php
        namespace StackExchangeMagentoRewrite;

        use MagentoSalesModelOrder;
        use MagentoFrameworkDataObject;

        class OrderSender extends MagentoSalesModelOrderEmailSenderOrderSender

        /**
        * @var MagentoCatalogApiProductRepositoryInterface
        */
        private $productRepository;

        public function __construct(
        MagentoSalesModelOrderEmailContainerTemplate $templateContainer,
        MagentoSalesModelOrderEmailContainerOrderIdentity $identityContainer,
        MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
        PsrLogLoggerInterface $logger,
        MagentoSalesModelOrderAddressRenderer $addressRenderer,
        MagentoPaymentHelperData $paymentHelper,
        MagentoSalesModelResourceModelOrder $orderResource,
        MagentoFrameworkAppConfigScopeConfigInterface $globalConfig,
        MagentoFrameworkEventManagerInterface $eventManager,
        MagentoCatalogApiProductRepositoryInterface $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 (MagentoFrameworkExceptionNoSuchEntityException $ex)
        continue;

        $categoryIds = array_merge($categoryIds,$product->getCategoryIds());

        $uniqueCategoryIds = array_unique($categoryIds);

        if(in_array($ConditionCategoryId, $categoryIds))
        return true;

        return false;








        share|improve this answer













        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="MagentoSalesModelOrderEmailSenderOrderSender" type="StackExchangeMagentoRewriteOrderSender" />
        </config>


        Rewrite class StackExchangeMagentoRewriteOrderSender.php



        And code is below:



        <?php
        namespace StackExchangeMagentoRewrite;

        use MagentoSalesModelOrder;
        use MagentoFrameworkDataObject;

        class OrderSender extends MagentoSalesModelOrderEmailSenderOrderSender

        /**
        * @var MagentoCatalogApiProductRepositoryInterface
        */
        private $productRepository;

        public function __construct(
        MagentoSalesModelOrderEmailContainerTemplate $templateContainer,
        MagentoSalesModelOrderEmailContainerOrderIdentity $identityContainer,
        MagentoSalesModelOrderEmailSenderBuilderFactory $senderBuilderFactory,
        PsrLogLoggerInterface $logger,
        MagentoSalesModelOrderAddressRenderer $addressRenderer,
        MagentoPaymentHelperData $paymentHelper,
        MagentoSalesModelResourceModelOrder $orderResource,
        MagentoFrameworkAppConfigScopeConfigInterface $globalConfig,
        MagentoFrameworkEventManagerInterface $eventManager,
        MagentoCatalogApiProductRepositoryInterface $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 (MagentoFrameworkExceptionNoSuchEntityException $ex)
        continue;

        $categoryIds = array_merge($categoryIds,$product->getCategoryIds());

        $uniqueCategoryIds = array_unique($categoryIds);

        if(in_array($ConditionCategoryId, $categoryIds))
        return true;

        return false;









        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered May 31 at 11:22









        Amit BeraAmit Bera

        60.9k1682181




        60.9k1682181



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f276726%2foverride-abstract-class%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

            Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?