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

                    Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                    Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                    Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form