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












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

      296211




      296211






















          3 Answers
          3






          active

          oldest

          votes


















          0














          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;
          use MagentoFrameworkAppObjectManager;

          class ObserverforAddCustomVariable implements ObserverInterface
          {

          protected $ruleFactory

          public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory) {
          $this->rulesFactory = $ruleFactory;
          }

          /**
          *
          * @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
          );


          /** @var $generator MagentoSalesRuleModelCouponMassgenerator */
          $generator = $this->_objectManager->get('MagentoSalesRuleModelCouponMassgenerator');
          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->_objectManager->get('PsrLogLoggerInterface')->critical($e);
          return false;
          } catch (Exception $e) {

          $this->_objectManager->get('PsrLogLoggerInterface')->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






          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









              0














              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;
              use MagentoFrameworkAppObjectManager;

              class ObserverforAddCustomVariable implements ObserverInterface
              {

              protected $ruleFactory

              public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory) {
              $this->rulesFactory = $ruleFactory;
              }

              /**
              *
              * @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
              );


              /** @var $generator MagentoSalesRuleModelCouponMassgenerator */
              $generator = $this->_objectManager->get('MagentoSalesRuleModelCouponMassgenerator');
              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->_objectManager->get('PsrLogLoggerInterface')->critical($e);
              return false;
              } catch (Exception $e) {

              $this->_objectManager->get('PsrLogLoggerInterface')->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






              share|improve this answer




























                0














                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;
                use MagentoFrameworkAppObjectManager;

                class ObserverforAddCustomVariable implements ObserverInterface
                {

                protected $ruleFactory

                public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory) {
                $this->rulesFactory = $ruleFactory;
                }

                /**
                *
                * @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
                );


                /** @var $generator MagentoSalesRuleModelCouponMassgenerator */
                $generator = $this->_objectManager->get('MagentoSalesRuleModelCouponMassgenerator');
                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->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                return false;
                } catch (Exception $e) {

                $this->_objectManager->get('PsrLogLoggerInterface')->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






                share|improve this answer


























                  0












                  0








                  0







                  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;
                  use MagentoFrameworkAppObjectManager;

                  class ObserverforAddCustomVariable implements ObserverInterface
                  {

                  protected $ruleFactory

                  public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory) {
                  $this->rulesFactory = $ruleFactory;
                  }

                  /**
                  *
                  * @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
                  );


                  /** @var $generator MagentoSalesRuleModelCouponMassgenerator */
                  $generator = $this->_objectManager->get('MagentoSalesRuleModelCouponMassgenerator');
                  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->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                  return false;
                  } catch (Exception $e) {

                  $this->_objectManager->get('PsrLogLoggerInterface')->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






                  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;
                  use MagentoFrameworkAppObjectManager;

                  class ObserverforAddCustomVariable implements ObserverInterface
                  {

                  protected $ruleFactory

                  public function __construct(MagentoSalesRuleModelRuleFactory $ruleFactory) {
                  $this->rulesFactory = $ruleFactory;
                  }

                  /**
                  *
                  * @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
                  );


                  /** @var $generator MagentoSalesRuleModelCouponMassgenerator */
                  $generator = $this->_objectManager->get('MagentoSalesRuleModelCouponMassgenerator');
                  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->_objectManager->get('PsrLogLoggerInterface')->critical($e);
                  return false;
                  } catch (Exception $e) {

                  $this->_objectManager->get('PsrLogLoggerInterface')->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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 13 '17 at 5:18









                  Amit BeraAmit Bera

                  57.4k1474171




                  57.4k1474171

























                      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

                          2,001220




                          2,001220










                          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

                              An IMO inspired problem

                              Management

                              Investment