Magento2: How to insert dynamic generated coupon code in email templateshow to add custom data in order email in magento 2Dynamic code for logo src for use in email templates, possibly using short tags?understanding the email templatesDocumentation for EMail templatesMagento2 override sales email templatesIssue on Gift card and cart prices rulesInsert custom variable into email templates in magento 2Share wishlist email not being sentMagento 2 Email templatesCreate a Free Shipping coupon in Cart Price Rules and works with Magento Shipping (M2)Free shipping code is not working for UPS in magento 2

size of pointers and architecture

To exponential digit growth and beyond!

How do I write real-world stories separate from my country of origin?

Why did Nick Fury not hesitate in blowing up the plane he thought was carrying a nuke?

Find this Unique UVC Palindrome ( ignoring signs and decimal) from Given Fractional Relationship

One word for 'the thing that attracts me'?

How do you earn the reader's trust?

Are clauses with "который" restrictive or non-restrictive by default?

What is the required burn to keep a satellite at a Lagrangian point?

Ratings matrix plot

Does science define life as "beginning at conception"?

Can a UK national work as a paid shop assistant in the USA?

Gas chromatography flame ionization detector (FID) - why hydrogen gas?

why "American-born", not "America-born"?

Can diplomats be allowed on the flight deck of a commercial European airline?

"Official wife" or "Formal wife"?

(For training purposes) Are there any openings with rook pawns that are more effective than others (and if so, what are they)?

Shell builtin `printf` line limit?

How does the Earth's center produce heat?

What pc resources are used when bruteforcing?

Three knights or knaves, three different hair colors

Why is this integration method not valid?

Is there a solution to paying high fees when opening and closing lightning channels once we hit a fee only market?

Why is this python script running in background consuming 100 % CPU?



Magento2: How to insert dynamic generated coupon code in email templates


how to add custom data in order email in magento 2Dynamic code for logo src for use in email templates, possibly using short tags?understanding the email templatesDocumentation for EMail templatesMagento2 override sales email templatesIssue on Gift card and cart prices rulesInsert custom variable into email templates in magento 2Share wishlist email not being sentMagento 2 Email templatesCreate a Free Shipping coupon in Cart Price Rules and works with Magento Shipping (M2)Free shipping code is not working for UPS in magento 2






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








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.










share|improve this question




























    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.










    share|improve this question
























      2












      2








      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.










      share|improve this question














      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.







      magento2 email-templates






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Oct 13 '17 at 0:24









      user1506075user1506075

      336314




      336314




















          3 Answers
          3






          active

          oldest

          votes


















          1














          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]ObserverObserverforAddCustomVariable" />
          </event>
          </config>


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



          <?php
          namespace [Vendor][ModuleName]Observer;
          use MagentoFrameworkEventObserverInterface;
          use MagentoFrameworkAppRequestDataPersistorInterface;

          class ObserverforAddCustomVariable implements ObserverInterface


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

          public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory,MagentoSalesRuleModelCouponMassgenerator $massgenerator, PsrLogLoggerInterface $logger )
          $this->ruleFactory= $ruleFactory;
          $this->massgenerator = $massgenerator;
          $this->logger = $logger;


          /**
          *
          * @param MagentoFrameworkEventObserver $observer
          * @return void
          */
          public function execute(MagentoFrameworkEventObserver $observer)

          /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $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 raw.



          how to add custom data in order email in magento 2






          share|improve this answer
































            0














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



            Just added $objectManager = MagentoFrameworkAppObjectManager::getInstance();



            And working fine.






            share|improve this answer
































              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(

              MagentoSalesRuleModelRuleFactory $ruleFactory,
              MagentoSalesRuleModelCouponMassgenerator $massGenerator

              )


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



              public function execute(MagentoFrameworkEventObserver $observer)

              /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $e)
              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
              return false;
              catch (Exception $e)

              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
              return false;







              share|improve this answer


















              • 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








              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%2f197071%2fmagento2-how-to-insert-dynamic-generated-coupon-code-in-email-templates%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              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]ObserverObserverforAddCustomVariable" />
              </event>
              </config>


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



              <?php
              namespace [Vendor][ModuleName]Observer;
              use MagentoFrameworkEventObserverInterface;
              use MagentoFrameworkAppRequestDataPersistorInterface;

              class ObserverforAddCustomVariable implements ObserverInterface


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

              public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory,MagentoSalesRuleModelCouponMassgenerator $massgenerator, PsrLogLoggerInterface $logger )
              $this->ruleFactory= $ruleFactory;
              $this->massgenerator = $massgenerator;
              $this->logger = $logger;


              /**
              *
              * @param MagentoFrameworkEventObserver $observer
              * @return void
              */
              public function execute(MagentoFrameworkEventObserver $observer)

              /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $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 raw.



              how to add custom data in order email in magento 2






              share|improve this answer





























                1














                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]ObserverObserverforAddCustomVariable" />
                </event>
                </config>


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



                <?php
                namespace [Vendor][ModuleName]Observer;
                use MagentoFrameworkEventObserverInterface;
                use MagentoFrameworkAppRequestDataPersistorInterface;

                class ObserverforAddCustomVariable implements ObserverInterface


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

                public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory,MagentoSalesRuleModelCouponMassgenerator $massgenerator, PsrLogLoggerInterface $logger )
                $this->ruleFactory= $ruleFactory;
                $this->massgenerator = $massgenerator;
                $this->logger = $logger;


                /**
                *
                * @param MagentoFrameworkEventObserver $observer
                * @return void
                */
                public function execute(MagentoFrameworkEventObserver $observer)

                /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $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 raw.



                how to add custom data in order email in magento 2






                share|improve this answer



























                  1












                  1








                  1







                  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]ObserverObserverforAddCustomVariable" />
                  </event>
                  </config>


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



                  <?php
                  namespace [Vendor][ModuleName]Observer;
                  use MagentoFrameworkEventObserverInterface;
                  use MagentoFrameworkAppRequestDataPersistorInterface;

                  class ObserverforAddCustomVariable implements ObserverInterface


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

                  public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory,MagentoSalesRuleModelCouponMassgenerator $massgenerator, PsrLogLoggerInterface $logger )
                  $this->ruleFactory= $ruleFactory;
                  $this->massgenerator = $massgenerator;
                  $this->logger = $logger;


                  /**
                  *
                  * @param MagentoFrameworkEventObserver $observer
                  * @return void
                  */
                  public function execute(MagentoFrameworkEventObserver $observer)

                  /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $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 raw.



                  how to add custom data in order email in magento 2






                  share|improve this answer















                  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]ObserverObserverforAddCustomVariable" />
                  </event>
                  </config>


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



                  <?php
                  namespace [Vendor][ModuleName]Observer;
                  use MagentoFrameworkEventObserverInterface;
                  use MagentoFrameworkAppRequestDataPersistorInterface;

                  class ObserverforAddCustomVariable implements ObserverInterface


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

                  public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory,MagentoSalesRuleModelCouponMassgenerator $massgenerator, PsrLogLoggerInterface $logger )
                  $this->ruleFactory= $ruleFactory;
                  $this->massgenerator = $massgenerator;
                  $this->logger = $logger;


                  /**
                  *
                  * @param MagentoFrameworkEventObserver $observer
                  * @return void
                  */
                  public function execute(MagentoFrameworkEventObserver $observer)

                  /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $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 raw.



                  how to add custom data in order email in magento 2







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 15 at 7:00









                  Khushbu

                  13113




                  13113










                  answered Oct 13 '17 at 5:18









                  Amit BeraAmit Bera

                  60.6k1682181




                  60.6k1682181























                      0














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



                      Just added $objectManager = MagentoFrameworkAppObjectManager::getInstance();



                      And working fine.






                      share|improve this answer





























                        0














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



                        Just added $objectManager = MagentoFrameworkAppObjectManager::getInstance();



                        And working fine.






                        share|improve this answer



























                          0












                          0








                          0







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



                          Just added $objectManager = MagentoFrameworkAppObjectManager::getInstance();



                          And working fine.






                          share|improve this answer















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



                          Just added $objectManager = MagentoFrameworkAppObjectManager::getInstance();



                          And working fine.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jun 22 '18 at 6:08









                          Chirag Patel

                          3,000626




                          3,000626










                          answered Jun 22 '18 at 5:58









                          DharmendraDharmendra

                          211




                          211





















                              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(

                              MagentoSalesRuleModelRuleFactory $ruleFactory,
                              MagentoSalesRuleModelCouponMassgenerator $massGenerator

                              )


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



                              public function execute(MagentoFrameworkEventObserver $observer)

                              /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $e)
                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;
                              catch (Exception $e)

                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;







                              share|improve this answer


















                              • 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
















                              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(

                              MagentoSalesRuleModelRuleFactory $ruleFactory,
                              MagentoSalesRuleModelCouponMassgenerator $massGenerator

                              )


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



                              public function execute(MagentoFrameworkEventObserver $observer)

                              /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $e)
                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;
                              catch (Exception $e)

                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;







                              share|improve this answer


















                              • 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














                              0












                              0








                              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(

                              MagentoSalesRuleModelRuleFactory $ruleFactory,
                              MagentoSalesRuleModelCouponMassgenerator $massGenerator

                              )


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



                              public function execute(MagentoFrameworkEventObserver $observer)

                              /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $e)
                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;
                              catch (Exception $e)

                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;







                              share|improve this answer













                              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(

                              MagentoSalesRuleModelRuleFactory $ruleFactory,
                              MagentoSalesRuleModelCouponMassgenerator $massGenerator

                              )


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



                              public function execute(MagentoFrameworkEventObserver $observer)

                              /** @var MagentoFrameworkAppActionAction $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 (MagentoFrameworkExceptionLocalizedException $e)
                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;
                              catch (Exception $e)

                              $this->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                              return false;








                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jun 22 '18 at 6:35









                              DharmendraDharmendra

                              211




                              211







                              • 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













                              • 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








                              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






                              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


















                              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%2f197071%2fmagento2-how-to-insert-dynamic-generated-coupon-code-in-email-templates%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?