2

Requirement: every time a customer place an order, a free shipping coupon will be sent which can only be used once.

So I need to insert the dynamic coupon code just like gift card code and abandoned cart rule coupon on normal email template.

Appreciate for any comment and solution.

3

Yes,it is possible.

  • Create A cart rules from admin>Marketing>Cart Rules.
  • Create a rules which will create dynamic coupon by selecting 'Use Auto Generation' for create multiple couple coupons.

During Creation setting should be :

enter image description here

Now,Add custom data in order email template in Magento 2 and create a coupon of the rule,you should fire run observer at event email_order_set_template_vars_before.

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

So, at this event you can add new parameter via transport to template means you can create coupon and send to email.

Just like: events.xml

<?xml version="1.0" encoding="utf-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="email_order_set_template_vars_before">
        <observer name="add_Custom_variable_to_Order" 
            instance="[Vendor]\[ModuleName]\Observer\ObserverforAddCustomVariable" />
    </event>
</config>

And at observer will create coupon and send to to email:

<?php
namespace [Vendor]\[ModuleName]\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;

class ObserverforAddCustomVariable implements ObserverInterface
{

    protected $ruleFactory;
    protected $massgenerator;
    protected $logger;

    public function __construct(\Magento\SalesRule\Model\RuleFactory $ruleFactory,\Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator, \Psr\Log\LoggerInterface $logger ) {
        $this->ruleFactory= $ruleFactory;
        $this->massgenerator = $massgenerator;
        $this->logger = $logger;
    }

    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /** @var \Magento\Framework\App\Action\Action $controller */
        $transport = $observer->getTransport();
        $couponCode = $this->createOneCoupon();
        if($couponCode){
            $transport['free-coupon'] = $couponCode;
        }
    }
    protected function createOneCoupon()
    {
        $ruleModel = $this->ruleFactory->create();
        $ruleModel->load({RulesID});
         try {
                $data = array(
                        'rule_id' => 1,
                        'qty' => 1,
                        'length' => '12',
                        'format' => 'alphanum',
                        'prefix' => 'free-shipping',
                        'suffix' => '',
                        'dash'=>0
                        );


                $generator = $this->massgenerator;
                if (!$generator->validateData($data)) {
                   return false;
                } else {
                    $generator->setData($data);
                    $generator->generatePool();
                    $generated = $generator->getGeneratedCount();
                    $codes = $generator->getGeneratedCodes();
                    return $codes[0];

                }
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->logger->critical($e);
                return false;
            } catch (\Exception $e) {

                $this->logger->critical($e);
                return false;
            }
    }

}

At the email template , you can get this custom variables free-coupon using {{var free-coupon|raw}}.

how to add custom data in order email in magento 2

0

Working fine.Thanks a lot.Only issue with object manager object.

Just added $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

And working fine.

0

We should not use Object manager to create object.

I did some miner changes in existing code and working fine. protected $ruleFactory; protected $massGenerator;

public function __construct(

\Magento\SalesRule\Model\RuleFactory $ruleFactory,
\Magento\SalesRule\Model\Coupon\Massgenerator  $massGenerator

    )
{

$this->rulesFactory = $ruleFactory;
$this->massGenerator = $massGenerator;

}

public function execute(\Magento\Framework\Event\Observer $observer)
{
  /** @var \Magento\Framework\App\Action\Action $controller */
    $transport = $observer->getTransport();
    $couponCode = $this->createOneCoupon();
    if($couponCode){
        $transport['couponcode'] = $couponCode;
    }

}  


protected function createOneCoupon()
{

     try {
            $data = array(
                    'rule_id' => 4,
                    'qty' => 1,
                    'length' => '12',
                    'format' => 'alphanum',
                    'prefix' => '',
                    'suffix' => '',
                    'dash'=>0
                    );


            if (!$this->massGenerator->validateData($data)) {
               return false;
            } else {
                $this->massGenerator->setData($data);
                $this->massGenerator->generatePool();
                $generated = $this->massGenerator->getGeneratedCount();
                $codes = $this->massGenerator->getGeneratedCodes();
                return $codes[0];

            }
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return false;
        } catch (\Exception $e) {

            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return false;
        }
}
1
  • 1
    Hello !! I suggest you to edit and update your code in your first answer instead of adding new/another answer for same question
    – Piyush
    Jun 22 '18 at 6:41

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.