2

I am trying to get the the shipping method using observer but I cant seem to get it to work, this is what I have for the ShippingTypeEmail.php

<?php

namespace vendor\Emails\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order;
class ShippingTypeEmail implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
        
    {
    $shpvar =''
    $order = $observer->getEvent()->getOrder();
    $ShpMethod = $order->getShippingMethod();
    if($ShpMethod == 'flatrate_flatrate'){
      $shpvar = 'flat'
    }else{
        $shpvar = 'collect'
    }
    }
}

Then I am using {{var shpvar|raw}} on the template

my event.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="vendor_emails_variable_order" instance="vendor\Emails\Observer\ShippingTypeEmail" />
    </event>
</config>

2 Answers 2

0

I suggest that you should use sales_order_save_after event to pull the shipping method instead of email_order_set_template_vars_before.

I hope this helps.

1
  • I presume if I use sales_order_save_after if an order email is resent it would not use the custom variable?
    – miller75
    Commented Oct 10, 2020 at 23:08
0

I got it working

<?php

namespace vendor\Emails\Observer;
use Magento\Framework\Event\ObserverInterface;

class ShippingTypeEmail implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {       
        $ShpMethod = $observer->getEvent()->getTransport();
    
        
        if($ShpMethod->getOrder()->getshippingmethod() == 'flatrate_flatrate')
        {
            $ShpMethod['shpvar']  = 'flat';
        }
        else{
            $ShpMethod['shpvar']  = 'collect';
    }
    }
}

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.