How to create Sales rule (Coupon) in magento 2 programmatically The 2019 Stack Overflow Developer Survey Results Are InMagento generate coupon codes programmaticallyCreate coupon for special productHow to create sales rule programmatically in Magento2Create coupon code programmatically (in Magento 2.x)How to create coupon for specific SKUmagento2.2 - programmatically create couponValidate and apply coupon when create an order programmaticallyCreate Coupon/Price rule for first 10 Customers .(Magento 2)Magento 2. How to Generate Coupon for specific product / products ProgrammaticallyHow to use Coupon in magento 2

Is bread bad for ducks?

Is "plugging out" electronic devices an American expression?

Why isn't airport relocation done gradually?

How to support a colleague who finds meetings extremely tiring?

How are circuits which use complex ICs normally simulated?

Did 3000BC Egyptians use meteoric iron weapons?

Deal with toxic manager when you can't quit

Origin of "cooter" meaning "vagina"

How to notate time signature switching consistently every measure

Is three citations per paragraph excessive for undergraduate research paper?

Are there incongruent pythagorean triangles with the same perimeter and same area?

Why did Acorn's A3000 have red function keys?

Can someone be penalized for an "unlawful" act if no penalty is specified?

Is this app Icon Browser Safe/Legit?

What is the meaning of the verb "bear" in this context?

Can you compress metal and what would be the consequences?

The difference between dialogue marks

Am I thawing this London Broil safely?

Multiply Two Integer Polynomials

What are the motivations for publishing new editions of an existing textbook, beyond new discoveries in a field?

How to save as into a customized destination on macOS?

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Are there any other methods to apply to solving simultaneous equations?

Button changing it's text & action. Good or terrible?



How to create Sales rule (Coupon) in magento 2 programmatically



The 2019 Stack Overflow Developer Survey Results Are InMagento generate coupon codes programmaticallyCreate coupon for special productHow to create sales rule programmatically in Magento2Create coupon code programmatically (in Magento 2.x)How to create coupon for specific SKUmagento2.2 - programmatically create couponValidate and apply coupon when create an order programmaticallyCreate Coupon/Price rule for first 10 Customers .(Magento 2)Magento 2. How to Generate Coupon for specific product / products ProgrammaticallyHow to use Coupon in magento 2



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








1















I created the coupon in function its works perfectly now I want to apply sales rules (apply on specific product) my code is



 public function setCoupon()

// $this->_state->setAreaCode('adminhtml');
// $this->_state->setAreaCode('frontend');


// $coupon['name'] = 'Offer_asad17';
$coupon['name'] = 'Sheikh';
$coupon['desc'] = 'Discount for vip signup coupon.';
$coupon['start'] = date('Y-m-d');
$coupon['end'] = '';
$coupon['max_redemptions'] = 1;
$coupon['discount_type'] ='by_fixed';
$coupon['discount_amount'] = 15;
$coupon['flag_is_free_shipping'] = 'no';
$coupon['redemptions'] = 1;
// $coupon['code'] ='NL017-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes
$coupon['code'] ='Sheikh-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes

$this->_rule->setName($coupon['name'])
->setDescription($coupon['desc'])
->setFromDate($coupon['start'])
->setToDate($coupon['end'])
->setUsesPerCustomer($coupon['max_redemptions'])
->setCustomerGroupIds(array('0','1','2','3',))
->setIsActive(1)
->setSimpleAction($coupon['discount_type'])
->setDiscountAmount($coupon['discount_amount'])
->setDiscountQty(1)
->setApplyToShipping($coupon['flag_is_free_shipping'])
->setTimesUsed($coupon['redemptions'])
->setWebsiteIds(array('1'))
->setCouponType(2)
// ->setProductIds(array('1','2','3'))
// ->setProductIds([1,2,3])
// ->setProductIds(array(1,2,3))
//->setProductIds([1,2,3])
// ->setProductIds('1')
->setProductIds(1)
->setCouponCode($coupon['code'])
->setUsesPerCoupon(NULL);
$this->_rule->save();










share|improve this question




























    1















    I created the coupon in function its works perfectly now I want to apply sales rules (apply on specific product) my code is



     public function setCoupon()

    // $this->_state->setAreaCode('adminhtml');
    // $this->_state->setAreaCode('frontend');


    // $coupon['name'] = 'Offer_asad17';
    $coupon['name'] = 'Sheikh';
    $coupon['desc'] = 'Discount for vip signup coupon.';
    $coupon['start'] = date('Y-m-d');
    $coupon['end'] = '';
    $coupon['max_redemptions'] = 1;
    $coupon['discount_type'] ='by_fixed';
    $coupon['discount_amount'] = 15;
    $coupon['flag_is_free_shipping'] = 'no';
    $coupon['redemptions'] = 1;
    // $coupon['code'] ='NL017-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes
    $coupon['code'] ='Sheikh-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes

    $this->_rule->setName($coupon['name'])
    ->setDescription($coupon['desc'])
    ->setFromDate($coupon['start'])
    ->setToDate($coupon['end'])
    ->setUsesPerCustomer($coupon['max_redemptions'])
    ->setCustomerGroupIds(array('0','1','2','3',))
    ->setIsActive(1)
    ->setSimpleAction($coupon['discount_type'])
    ->setDiscountAmount($coupon['discount_amount'])
    ->setDiscountQty(1)
    ->setApplyToShipping($coupon['flag_is_free_shipping'])
    ->setTimesUsed($coupon['redemptions'])
    ->setWebsiteIds(array('1'))
    ->setCouponType(2)
    // ->setProductIds(array('1','2','3'))
    // ->setProductIds([1,2,3])
    // ->setProductIds(array(1,2,3))
    //->setProductIds([1,2,3])
    // ->setProductIds('1')
    ->setProductIds(1)
    ->setCouponCode($coupon['code'])
    ->setUsesPerCoupon(NULL);
    $this->_rule->save();










    share|improve this question
























      1












      1








      1








      I created the coupon in function its works perfectly now I want to apply sales rules (apply on specific product) my code is



       public function setCoupon()

      // $this->_state->setAreaCode('adminhtml');
      // $this->_state->setAreaCode('frontend');


      // $coupon['name'] = 'Offer_asad17';
      $coupon['name'] = 'Sheikh';
      $coupon['desc'] = 'Discount for vip signup coupon.';
      $coupon['start'] = date('Y-m-d');
      $coupon['end'] = '';
      $coupon['max_redemptions'] = 1;
      $coupon['discount_type'] ='by_fixed';
      $coupon['discount_amount'] = 15;
      $coupon['flag_is_free_shipping'] = 'no';
      $coupon['redemptions'] = 1;
      // $coupon['code'] ='NL017-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes
      $coupon['code'] ='Sheikh-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes

      $this->_rule->setName($coupon['name'])
      ->setDescription($coupon['desc'])
      ->setFromDate($coupon['start'])
      ->setToDate($coupon['end'])
      ->setUsesPerCustomer($coupon['max_redemptions'])
      ->setCustomerGroupIds(array('0','1','2','3',))
      ->setIsActive(1)
      ->setSimpleAction($coupon['discount_type'])
      ->setDiscountAmount($coupon['discount_amount'])
      ->setDiscountQty(1)
      ->setApplyToShipping($coupon['flag_is_free_shipping'])
      ->setTimesUsed($coupon['redemptions'])
      ->setWebsiteIds(array('1'))
      ->setCouponType(2)
      // ->setProductIds(array('1','2','3'))
      // ->setProductIds([1,2,3])
      // ->setProductIds(array(1,2,3))
      //->setProductIds([1,2,3])
      // ->setProductIds('1')
      ->setProductIds(1)
      ->setCouponCode($coupon['code'])
      ->setUsesPerCoupon(NULL);
      $this->_rule->save();










      share|improve this question














      I created the coupon in function its works perfectly now I want to apply sales rules (apply on specific product) my code is



       public function setCoupon()

      // $this->_state->setAreaCode('adminhtml');
      // $this->_state->setAreaCode('frontend');


      // $coupon['name'] = 'Offer_asad17';
      $coupon['name'] = 'Sheikh';
      $coupon['desc'] = 'Discount for vip signup coupon.';
      $coupon['start'] = date('Y-m-d');
      $coupon['end'] = '';
      $coupon['max_redemptions'] = 1;
      $coupon['discount_type'] ='by_fixed';
      $coupon['discount_amount'] = 15;
      $coupon['flag_is_free_shipping'] = 'no';
      $coupon['redemptions'] = 1;
      // $coupon['code'] ='NL017-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes
      $coupon['code'] ='Sheikh-1234'; //this code will normally be autogenerated but i am hard coding for testing purposes

      $this->_rule->setName($coupon['name'])
      ->setDescription($coupon['desc'])
      ->setFromDate($coupon['start'])
      ->setToDate($coupon['end'])
      ->setUsesPerCustomer($coupon['max_redemptions'])
      ->setCustomerGroupIds(array('0','1','2','3',))
      ->setIsActive(1)
      ->setSimpleAction($coupon['discount_type'])
      ->setDiscountAmount($coupon['discount_amount'])
      ->setDiscountQty(1)
      ->setApplyToShipping($coupon['flag_is_free_shipping'])
      ->setTimesUsed($coupon['redemptions'])
      ->setWebsiteIds(array('1'))
      ->setCouponType(2)
      // ->setProductIds(array('1','2','3'))
      // ->setProductIds([1,2,3])
      // ->setProductIds(array(1,2,3))
      //->setProductIds([1,2,3])
      // ->setProductIds('1')
      ->setProductIds(1)
      ->setCouponCode($coupon['code'])
      ->setUsesPerCoupon(NULL);
      $this->_rule->save();







      magento2 frontend backend coupon






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 13:18









      Asad KhanAsad Khan

      1698




      1698




















          1 Answer
          1






          active

          oldest

          votes


















          0














          try this my friend, this code to add rules before create coupon



          use MagentoSalesRuleModelRuleFactory;

          protected $_ruleFactory;

          public function __construct(
          Context $context,
          RuleFactory $ruleFactory
          )

          $this->_ruleRepostitory = $ruleRepostitory;
          parent::__construct($context);



          public function execute()

          $ruleModel = $this->_ruleFactory->create();
          $ruleModel->setName($getRule->getName())
          ->setDescription($getRule->getDescription())
          ->setCouponCode($getCoupon['code'])
          ->setFromDate($getRule->getFromDate())
          ->setToDate($getRule->getFromDate())
          ->setUsesPerCustomer($getRule->getUsesPerCustomer())
          ->setCustomerGroupIds($getRule->getCustomerGroupIds())
          ->setIsActive($getRule->getIsActive())
          ->setStopRulesProcessing($getRule->getStopRulesProcessing())
          ->setIsAdvanced($getRule->getIsAdvanced())
          ->setProductIds($getRule->getProductIds())
          ->setSortOrder($getRule->getSortOrder())
          ->setSimpleAction($getRule->getSimpleAction())
          ->setDiscountAmount($getRule->getDiscountAmount())
          ->setDiscountQty($getRule->getDiscountQty())
          ->setDiscountStep($getRule->getDiscountStep())
          ->setSimpleFreeShipping($getRule->getSimpleFreeShipping())
          ->setApplyToShipping($getRule->getApplyToShipping())
          ->setTimesUsed($getRule->getTimesUsed())
          ->setIsRss($getRule->getIsRss())
          ->setWebsiteIds($getRule->getWebsiteIds())
          ->setCouponType(2)
          ->setUsesPerCoupon($getRule->getUsesPerCoupon());
          $ruleModel->save();




          Remember, change " $getRule->... " = your data, good luck






          share|improve this answer

























            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%2f266838%2fhow-to-create-sales-rule-coupon-in-magento-2-programmatically%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            try this my friend, this code to add rules before create coupon



            use MagentoSalesRuleModelRuleFactory;

            protected $_ruleFactory;

            public function __construct(
            Context $context,
            RuleFactory $ruleFactory
            )

            $this->_ruleRepostitory = $ruleRepostitory;
            parent::__construct($context);



            public function execute()

            $ruleModel = $this->_ruleFactory->create();
            $ruleModel->setName($getRule->getName())
            ->setDescription($getRule->getDescription())
            ->setCouponCode($getCoupon['code'])
            ->setFromDate($getRule->getFromDate())
            ->setToDate($getRule->getFromDate())
            ->setUsesPerCustomer($getRule->getUsesPerCustomer())
            ->setCustomerGroupIds($getRule->getCustomerGroupIds())
            ->setIsActive($getRule->getIsActive())
            ->setStopRulesProcessing($getRule->getStopRulesProcessing())
            ->setIsAdvanced($getRule->getIsAdvanced())
            ->setProductIds($getRule->getProductIds())
            ->setSortOrder($getRule->getSortOrder())
            ->setSimpleAction($getRule->getSimpleAction())
            ->setDiscountAmount($getRule->getDiscountAmount())
            ->setDiscountQty($getRule->getDiscountQty())
            ->setDiscountStep($getRule->getDiscountStep())
            ->setSimpleFreeShipping($getRule->getSimpleFreeShipping())
            ->setApplyToShipping($getRule->getApplyToShipping())
            ->setTimesUsed($getRule->getTimesUsed())
            ->setIsRss($getRule->getIsRss())
            ->setWebsiteIds($getRule->getWebsiteIds())
            ->setCouponType(2)
            ->setUsesPerCoupon($getRule->getUsesPerCoupon());
            $ruleModel->save();




            Remember, change " $getRule->... " = your data, good luck






            share|improve this answer





























              0














              try this my friend, this code to add rules before create coupon



              use MagentoSalesRuleModelRuleFactory;

              protected $_ruleFactory;

              public function __construct(
              Context $context,
              RuleFactory $ruleFactory
              )

              $this->_ruleRepostitory = $ruleRepostitory;
              parent::__construct($context);



              public function execute()

              $ruleModel = $this->_ruleFactory->create();
              $ruleModel->setName($getRule->getName())
              ->setDescription($getRule->getDescription())
              ->setCouponCode($getCoupon['code'])
              ->setFromDate($getRule->getFromDate())
              ->setToDate($getRule->getFromDate())
              ->setUsesPerCustomer($getRule->getUsesPerCustomer())
              ->setCustomerGroupIds($getRule->getCustomerGroupIds())
              ->setIsActive($getRule->getIsActive())
              ->setStopRulesProcessing($getRule->getStopRulesProcessing())
              ->setIsAdvanced($getRule->getIsAdvanced())
              ->setProductIds($getRule->getProductIds())
              ->setSortOrder($getRule->getSortOrder())
              ->setSimpleAction($getRule->getSimpleAction())
              ->setDiscountAmount($getRule->getDiscountAmount())
              ->setDiscountQty($getRule->getDiscountQty())
              ->setDiscountStep($getRule->getDiscountStep())
              ->setSimpleFreeShipping($getRule->getSimpleFreeShipping())
              ->setApplyToShipping($getRule->getApplyToShipping())
              ->setTimesUsed($getRule->getTimesUsed())
              ->setIsRss($getRule->getIsRss())
              ->setWebsiteIds($getRule->getWebsiteIds())
              ->setCouponType(2)
              ->setUsesPerCoupon($getRule->getUsesPerCoupon());
              $ruleModel->save();




              Remember, change " $getRule->... " = your data, good luck






              share|improve this answer



























                0












                0








                0







                try this my friend, this code to add rules before create coupon



                use MagentoSalesRuleModelRuleFactory;

                protected $_ruleFactory;

                public function __construct(
                Context $context,
                RuleFactory $ruleFactory
                )

                $this->_ruleRepostitory = $ruleRepostitory;
                parent::__construct($context);



                public function execute()

                $ruleModel = $this->_ruleFactory->create();
                $ruleModel->setName($getRule->getName())
                ->setDescription($getRule->getDescription())
                ->setCouponCode($getCoupon['code'])
                ->setFromDate($getRule->getFromDate())
                ->setToDate($getRule->getFromDate())
                ->setUsesPerCustomer($getRule->getUsesPerCustomer())
                ->setCustomerGroupIds($getRule->getCustomerGroupIds())
                ->setIsActive($getRule->getIsActive())
                ->setStopRulesProcessing($getRule->getStopRulesProcessing())
                ->setIsAdvanced($getRule->getIsAdvanced())
                ->setProductIds($getRule->getProductIds())
                ->setSortOrder($getRule->getSortOrder())
                ->setSimpleAction($getRule->getSimpleAction())
                ->setDiscountAmount($getRule->getDiscountAmount())
                ->setDiscountQty($getRule->getDiscountQty())
                ->setDiscountStep($getRule->getDiscountStep())
                ->setSimpleFreeShipping($getRule->getSimpleFreeShipping())
                ->setApplyToShipping($getRule->getApplyToShipping())
                ->setTimesUsed($getRule->getTimesUsed())
                ->setIsRss($getRule->getIsRss())
                ->setWebsiteIds($getRule->getWebsiteIds())
                ->setCouponType(2)
                ->setUsesPerCoupon($getRule->getUsesPerCoupon());
                $ruleModel->save();




                Remember, change " $getRule->... " = your data, good luck






                share|improve this answer















                try this my friend, this code to add rules before create coupon



                use MagentoSalesRuleModelRuleFactory;

                protected $_ruleFactory;

                public function __construct(
                Context $context,
                RuleFactory $ruleFactory
                )

                $this->_ruleRepostitory = $ruleRepostitory;
                parent::__construct($context);



                public function execute()

                $ruleModel = $this->_ruleFactory->create();
                $ruleModel->setName($getRule->getName())
                ->setDescription($getRule->getDescription())
                ->setCouponCode($getCoupon['code'])
                ->setFromDate($getRule->getFromDate())
                ->setToDate($getRule->getFromDate())
                ->setUsesPerCustomer($getRule->getUsesPerCustomer())
                ->setCustomerGroupIds($getRule->getCustomerGroupIds())
                ->setIsActive($getRule->getIsActive())
                ->setStopRulesProcessing($getRule->getStopRulesProcessing())
                ->setIsAdvanced($getRule->getIsAdvanced())
                ->setProductIds($getRule->getProductIds())
                ->setSortOrder($getRule->getSortOrder())
                ->setSimpleAction($getRule->getSimpleAction())
                ->setDiscountAmount($getRule->getDiscountAmount())
                ->setDiscountQty($getRule->getDiscountQty())
                ->setDiscountStep($getRule->getDiscountStep())
                ->setSimpleFreeShipping($getRule->getSimpleFreeShipping())
                ->setApplyToShipping($getRule->getApplyToShipping())
                ->setTimesUsed($getRule->getTimesUsed())
                ->setIsRss($getRule->getIsRss())
                ->setWebsiteIds($getRule->getWebsiteIds())
                ->setCouponType(2)
                ->setUsesPerCoupon($getRule->getUsesPerCoupon());
                $ruleModel->save();




                Remember, change " $getRule->... " = your data, good luck







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited yesterday

























                answered yesterday









                wightmanwightman

                63




                63



























                    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%2f266838%2fhow-to-create-sales-rule-coupon-in-magento-2-programmatically%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?