0

I want to send Email in Magento 2 when order status change in ( Cancel and Hold )

My current code is :

<?php

namespace Hlemail\Customemail\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender;

class OrderSaveAfter implements ObserverInterface
{

protected $orderCommentSender;

public function __construct(
    OrderCommentSender $orderCommentSender
)
{
    $this->orderCommentSender = $orderCommentSender;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $order = $observer->getEvent()->getOrder();
    if ($order->getState() == 'canceled') {
        $this->orderCommentSender->send($order, true);
    }
}
}

How to send email to Admin. Any help is appriciated.

1

1 Answer 1

1

Refer sales_order_save_after event.

In observer, you can get the state of order:

Observer/SalesOrderAfterSave.php

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $order = $observer->getEvent()->getOrder();
    if ($order instanceof \Magento\Framework\Model\AbstractModel) {
       if($order->getState() == 'canceled' || $order->getState() == 'closed') {
            //Your code here
       }
    }
    return $this;
}

If you want to transform or update the data then you should use the plugin.

etc/di.xml

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

    <type name="Magento\Sales\Api\OrderRepositoryInterface">
        <plugin name="order_state_plugin"
                type="Vendor\Module\Model\OrderStatePlugin"/>
    </type>

</config>

Model\Plugin\OrderStatePlugin.php

<?php

namespace Vendor\Module\Plugin;

class OrderStatePlugin
{
/**
 * @param \Magento\Sales\Api\OrderRepositoryInterface $subject
 * @param \Magento\Sales\Api\Data\OrderInterface $result
 * @return mixed
 * @throws \Exception
 */
public function afterSave(
    \Magento\Sales\Api\OrderRepositoryInterface $subject,
    $result
) {
    if($result->getState() == Order::STATE_COMPLETE) {
        ......
    }
    return $result;
}
4
  • Thanks for your answer @Hamendra i need to send new mail template when status is changed .
    – Prits
    Commented Jun 22, 2021 at 4:58
  • You can send, just create an helper file & add code there call helper method in observer file. Commented Jun 22, 2021 at 5:15
  • @Prits use this link to send email codextblog.com/magento-2/…
    – Devidas
    Commented Jun 22, 2021 at 7:05
  • by using the above answer
    – Devidas
    Commented Jun 22, 2021 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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