Create coupon code programmatically (in Magento 2.x) The 2019 Stack Overflow Developer Survey...

Aging parents with no investments

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

Can a rogue use sneak attack with weapons that have the thrown property even if they are not thrown?

Have you ever entered Singapore using a different passport or name?

Why was M87 targetted for the Event Horizon Telescope instead of Sagittarius A*?

How to support a colleague who finds meetings extremely tiring?

What does Linus Torvalds mean when he says that Git "never ever" tracks a file?

Time travel alters history but people keep saying nothing's changed

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

Identify This Plant (Flower)

Can we generate random numbers using irrational numbers like π and e?

How come people say “Would of”?

What did it mean to "align" a radio?

"as much details as you can remember"

Can a flute soloist sit?

What do hard-Brexiteers want with respect to the Irish border?

Can you compress metal and what would be the consequences?

Am I thawing this London Broil safely?

Are children permitted to help build the Beis Hamikdash?

Where to refill my bottle in India?

Why hard-Brexiteers don't insist on a hard border to prevent illegal immigration after Brexit?

Does the shape of a die affect the probability of a number being rolled?

Earliest use of the term "Galois extension"?

Did 3000BC Egyptians use meteoric iron weapons?



Create coupon code programmatically (in Magento 2.x)



The 2019 Stack Overflow Developer Survey Results Are InUsing Solr search with Magento EE 1.13Magento Community - Coupon Code FunctionalityDealing with “Lock wait timeout exceeded; try restarting transaction” error in Percona ServerMagento duplicate the product getting innodb lock timeout errorError when saving productsMagento 2 Migration From custom tables (non-magento) to magento 2Magento2: Lock wait timeout exceeded - catalog_product_entity - loading productsmagento2.2 - programmatically create couponAdvanced Reporting Extension Errormagento 2 errors : General error: 1205 Lock wait timeout exceeded; try restarting transaction





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







2















I'm trying to port over tens of thousands of coupons from a custom e-commerce website into Magento 2.0.8 and I'm having a hard time getting it to work. These are simple coupons either fixed $ or % off of the carts subtotal. I have been unable to get it to save from the command line.



I have a command called coupons:migrate that I'm running this code in. This is what I have so far in my createCoupon method that accepts the current coupons row (looping over a CSV file):



protected function createCoupon($coupon) {
$shoppingCartPriceRule = $this->objectManager->create('MagentoSalesRuleModelRule');

$shoppingCartPriceRule->setName($coupon['name'])
->setDescription($coupon['name'])
->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')
->setCouponCode($coupon['code'])
->setUsesPerCoupon(NULL);

return $shoppingCartPriceRule->save();

}


I'm currently getting this error from my database:



[Zend_Db_Statement_Exception]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: INSERT INTO `magento_reward_salesrule` (`rule_id`,`points_delta`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `points_delta` = VALUES
(`points_delta`)

[PDOException]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction


Any help would be greatly appreciated. I'm basically stuck now.










share|improve this question
















bumped to the homepage by Community 12 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
















  • How about your current issue?

    – Khoa TruongDinh
    Aug 26 '16 at 14:25











  • @B.Mackswell, did the answer help you to solve the problem? If so, please accept the answer. If not, please inform us.

    – 7ochem
    Oct 10 '16 at 7:03


















2















I'm trying to port over tens of thousands of coupons from a custom e-commerce website into Magento 2.0.8 and I'm having a hard time getting it to work. These are simple coupons either fixed $ or % off of the carts subtotal. I have been unable to get it to save from the command line.



I have a command called coupons:migrate that I'm running this code in. This is what I have so far in my createCoupon method that accepts the current coupons row (looping over a CSV file):



protected function createCoupon($coupon) {
$shoppingCartPriceRule = $this->objectManager->create('MagentoSalesRuleModelRule');

$shoppingCartPriceRule->setName($coupon['name'])
->setDescription($coupon['name'])
->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')
->setCouponCode($coupon['code'])
->setUsesPerCoupon(NULL);

return $shoppingCartPriceRule->save();

}


I'm currently getting this error from my database:



[Zend_Db_Statement_Exception]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: INSERT INTO `magento_reward_salesrule` (`rule_id`,`points_delta`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `points_delta` = VALUES
(`points_delta`)

[PDOException]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction


Any help would be greatly appreciated. I'm basically stuck now.










share|improve this question
















bumped to the homepage by Community 12 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
















  • How about your current issue?

    – Khoa TruongDinh
    Aug 26 '16 at 14:25











  • @B.Mackswell, did the answer help you to solve the problem? If so, please accept the answer. If not, please inform us.

    – 7ochem
    Oct 10 '16 at 7:03














2












2








2


1






I'm trying to port over tens of thousands of coupons from a custom e-commerce website into Magento 2.0.8 and I'm having a hard time getting it to work. These are simple coupons either fixed $ or % off of the carts subtotal. I have been unable to get it to save from the command line.



I have a command called coupons:migrate that I'm running this code in. This is what I have so far in my createCoupon method that accepts the current coupons row (looping over a CSV file):



protected function createCoupon($coupon) {
$shoppingCartPriceRule = $this->objectManager->create('MagentoSalesRuleModelRule');

$shoppingCartPriceRule->setName($coupon['name'])
->setDescription($coupon['name'])
->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')
->setCouponCode($coupon['code'])
->setUsesPerCoupon(NULL);

return $shoppingCartPriceRule->save();

}


I'm currently getting this error from my database:



[Zend_Db_Statement_Exception]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: INSERT INTO `magento_reward_salesrule` (`rule_id`,`points_delta`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `points_delta` = VALUES
(`points_delta`)

[PDOException]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction


Any help would be greatly appreciated. I'm basically stuck now.










share|improve this question
















I'm trying to port over tens of thousands of coupons from a custom e-commerce website into Magento 2.0.8 and I'm having a hard time getting it to work. These are simple coupons either fixed $ or % off of the carts subtotal. I have been unable to get it to save from the command line.



I have a command called coupons:migrate that I'm running this code in. This is what I have so far in my createCoupon method that accepts the current coupons row (looping over a CSV file):



protected function createCoupon($coupon) {
$shoppingCartPriceRule = $this->objectManager->create('MagentoSalesRuleModelRule');

$shoppingCartPriceRule->setName($coupon['name'])
->setDescription($coupon['name'])
->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')
->setCouponCode($coupon['code'])
->setUsesPerCoupon(NULL);

return $shoppingCartPriceRule->save();

}


I'm currently getting this error from my database:



[Zend_Db_Statement_Exception]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: INSERT INTO `magento_reward_salesrule` (`rule_id`,`points_delta`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `points_delta` = VALUES
(`points_delta`)

[PDOException]
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction


Any help would be greatly appreciated. I'm basically stuck now.







magento2 database error shopping-cart-price-rules coupon






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 10 '16 at 7:01









7ochem

5,84493768




5,84493768










asked Aug 17 '16 at 21:45









b. mackswellb. mackswell

112




112





bumped to the homepage by Community 12 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 12 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • How about your current issue?

    – Khoa TruongDinh
    Aug 26 '16 at 14:25











  • @B.Mackswell, did the answer help you to solve the problem? If so, please accept the answer. If not, please inform us.

    – 7ochem
    Oct 10 '16 at 7:03



















  • How about your current issue?

    – Khoa TruongDinh
    Aug 26 '16 at 14:25











  • @B.Mackswell, did the answer help you to solve the problem? If so, please accept the answer. If not, please inform us.

    – 7ochem
    Oct 10 '16 at 7:03

















How about your current issue?

– Khoa TruongDinh
Aug 26 '16 at 14:25





How about your current issue?

– Khoa TruongDinh
Aug 26 '16 at 14:25













@B.Mackswell, did the answer help you to solve the problem? If so, please accept the answer. If not, please inform us.

– 7ochem
Oct 10 '16 at 7:03





@B.Mackswell, did the answer help you to solve the problem? If so, please accept the answer. If not, please inform us.

– 7ochem
Oct 10 '16 at 7:03










3 Answers
3






active

oldest

votes


















0














I don't try to test your code, however, seem that your code lines need to improve the performance. After saving the object model, we need to unset the data object:



$shoppingCartPriceRule->save()
$shoppingCartPriceRule->unsetData();





share|improve this answer































    0














    You can try below code:



    protected $ruleFactory

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


    $ruleData = [
    "name" => "Buy 3 tee shirts and get the 4th free",
    "description" => "Buy 3 tee shirts and get the 4th free",
    "from_date" => null,
    "to_date" => null,
    "uses_per_customer" => "0",
    "is_active" => "1",
    "stop_rules_processing" => "0",
    "is_advanced" => "1",
    "product_ids" => null,
    "sort_order" => "0",
    "simple_action" => "buy_x_get_y",
    "discount_amount" => "1.0000",
    "discount_qty" => null,
    "discount_step" => "3",
    "apply_to_shipping" => "0",
    "times_used" => "0",
    "is_rss" => "1",
    "coupon_type" => "NO_COUPON",
    "use_auto_generation" => "0",
    "uses_per_coupon" => "0",
    "simple_free_shipping" => "0",
    "customer_group_ids" => [0, 1, 2, 3],
    "website_ids" => [1],
    "coupon_code" => null,
    "store_labels" => [],
    "conditions_serialized" => '',
    "actions_serialized" => ''
    ];

    $ruleModel = $this->ruleFactory->create();
    $ruleModel->setData($ruleData);
    $ruleModel->save();





    share|improve this answer

































      0














      Try code below



      $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
      $state = $objectManager->get('MagentoFrameworkAppState');
      $state->setAreaCode('adminhtml');

      $coupon['name'] = 'test';
      $coupon['desc'] = 'Discount for Test';
      $coupon['start'] = date('Y-m-d');
      $coupon['end'] = '';
      $coupon['max_redemptions'] = 1;
      $coupon['discount_type'] = 'by_percent';
      $coupon['discount_amount'] = 15;
      $coupon['flag_is_free_shipping'] = 'no';
      $coupon['redemptions'] = 1;
      $coupon['code'] = 'test-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

      $shoppingCartPriceRule = $objectManager->create('MagentoSalesRuleModelRule');
      $shoppingCartPriceRule->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)
      ->setCouponCode($coupon['code'])
      ->setUsesPerCoupon(NULL);
      $shoppingCartPriceRule->save();





      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%2f131869%2fcreate-coupon-code-programmatically-in-magento-2-x%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














        I don't try to test your code, however, seem that your code lines need to improve the performance. After saving the object model, we need to unset the data object:



        $shoppingCartPriceRule->save()
        $shoppingCartPriceRule->unsetData();





        share|improve this answer




























          0














          I don't try to test your code, however, seem that your code lines need to improve the performance. After saving the object model, we need to unset the data object:



          $shoppingCartPriceRule->save()
          $shoppingCartPriceRule->unsetData();





          share|improve this answer


























            0












            0








            0







            I don't try to test your code, however, seem that your code lines need to improve the performance. After saving the object model, we need to unset the data object:



            $shoppingCartPriceRule->save()
            $shoppingCartPriceRule->unsetData();





            share|improve this answer













            I don't try to test your code, however, seem that your code lines need to improve the performance. After saving the object model, we need to unset the data object:



            $shoppingCartPriceRule->save()
            $shoppingCartPriceRule->unsetData();






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 18 '16 at 13:41









            Khoa TruongDinhKhoa TruongDinh

            22.2k64187




            22.2k64187

























                0














                You can try below code:



                protected $ruleFactory

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


                $ruleData = [
                "name" => "Buy 3 tee shirts and get the 4th free",
                "description" => "Buy 3 tee shirts and get the 4th free",
                "from_date" => null,
                "to_date" => null,
                "uses_per_customer" => "0",
                "is_active" => "1",
                "stop_rules_processing" => "0",
                "is_advanced" => "1",
                "product_ids" => null,
                "sort_order" => "0",
                "simple_action" => "buy_x_get_y",
                "discount_amount" => "1.0000",
                "discount_qty" => null,
                "discount_step" => "3",
                "apply_to_shipping" => "0",
                "times_used" => "0",
                "is_rss" => "1",
                "coupon_type" => "NO_COUPON",
                "use_auto_generation" => "0",
                "uses_per_coupon" => "0",
                "simple_free_shipping" => "0",
                "customer_group_ids" => [0, 1, 2, 3],
                "website_ids" => [1],
                "coupon_code" => null,
                "store_labels" => [],
                "conditions_serialized" => '',
                "actions_serialized" => ''
                ];

                $ruleModel = $this->ruleFactory->create();
                $ruleModel->setData($ruleData);
                $ruleModel->save();





                share|improve this answer






























                  0














                  You can try below code:



                  protected $ruleFactory

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


                  $ruleData = [
                  "name" => "Buy 3 tee shirts and get the 4th free",
                  "description" => "Buy 3 tee shirts and get the 4th free",
                  "from_date" => null,
                  "to_date" => null,
                  "uses_per_customer" => "0",
                  "is_active" => "1",
                  "stop_rules_processing" => "0",
                  "is_advanced" => "1",
                  "product_ids" => null,
                  "sort_order" => "0",
                  "simple_action" => "buy_x_get_y",
                  "discount_amount" => "1.0000",
                  "discount_qty" => null,
                  "discount_step" => "3",
                  "apply_to_shipping" => "0",
                  "times_used" => "0",
                  "is_rss" => "1",
                  "coupon_type" => "NO_COUPON",
                  "use_auto_generation" => "0",
                  "uses_per_coupon" => "0",
                  "simple_free_shipping" => "0",
                  "customer_group_ids" => [0, 1, 2, 3],
                  "website_ids" => [1],
                  "coupon_code" => null,
                  "store_labels" => [],
                  "conditions_serialized" => '',
                  "actions_serialized" => ''
                  ];

                  $ruleModel = $this->ruleFactory->create();
                  $ruleModel->setData($ruleData);
                  $ruleModel->save();





                  share|improve this answer




























                    0












                    0








                    0







                    You can try below code:



                    protected $ruleFactory

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


                    $ruleData = [
                    "name" => "Buy 3 tee shirts and get the 4th free",
                    "description" => "Buy 3 tee shirts and get the 4th free",
                    "from_date" => null,
                    "to_date" => null,
                    "uses_per_customer" => "0",
                    "is_active" => "1",
                    "stop_rules_processing" => "0",
                    "is_advanced" => "1",
                    "product_ids" => null,
                    "sort_order" => "0",
                    "simple_action" => "buy_x_get_y",
                    "discount_amount" => "1.0000",
                    "discount_qty" => null,
                    "discount_step" => "3",
                    "apply_to_shipping" => "0",
                    "times_used" => "0",
                    "is_rss" => "1",
                    "coupon_type" => "NO_COUPON",
                    "use_auto_generation" => "0",
                    "uses_per_coupon" => "0",
                    "simple_free_shipping" => "0",
                    "customer_group_ids" => [0, 1, 2, 3],
                    "website_ids" => [1],
                    "coupon_code" => null,
                    "store_labels" => [],
                    "conditions_serialized" => '',
                    "actions_serialized" => ''
                    ];

                    $ruleModel = $this->ruleFactory->create();
                    $ruleModel->setData($ruleData);
                    $ruleModel->save();





                    share|improve this answer















                    You can try below code:



                    protected $ruleFactory

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


                    $ruleData = [
                    "name" => "Buy 3 tee shirts and get the 4th free",
                    "description" => "Buy 3 tee shirts and get the 4th free",
                    "from_date" => null,
                    "to_date" => null,
                    "uses_per_customer" => "0",
                    "is_active" => "1",
                    "stop_rules_processing" => "0",
                    "is_advanced" => "1",
                    "product_ids" => null,
                    "sort_order" => "0",
                    "simple_action" => "buy_x_get_y",
                    "discount_amount" => "1.0000",
                    "discount_qty" => null,
                    "discount_step" => "3",
                    "apply_to_shipping" => "0",
                    "times_used" => "0",
                    "is_rss" => "1",
                    "coupon_type" => "NO_COUPON",
                    "use_auto_generation" => "0",
                    "uses_per_coupon" => "0",
                    "simple_free_shipping" => "0",
                    "customer_group_ids" => [0, 1, 2, 3],
                    "website_ids" => [1],
                    "coupon_code" => null,
                    "store_labels" => [],
                    "conditions_serialized" => '',
                    "actions_serialized" => ''
                    ];

                    $ruleModel = $this->ruleFactory->create();
                    $ruleModel->setData($ruleData);
                    $ruleModel->save();






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 10 '18 at 8:23

























                    answered Nov 14 '17 at 18:07









                    Sunil PatelSunil Patel

                    1,3681612




                    1,3681612























                        0














                        Try code below



                        $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
                        $state = $objectManager->get('MagentoFrameworkAppState');
                        $state->setAreaCode('adminhtml');

                        $coupon['name'] = 'test';
                        $coupon['desc'] = 'Discount for Test';
                        $coupon['start'] = date('Y-m-d');
                        $coupon['end'] = '';
                        $coupon['max_redemptions'] = 1;
                        $coupon['discount_type'] = 'by_percent';
                        $coupon['discount_amount'] = 15;
                        $coupon['flag_is_free_shipping'] = 'no';
                        $coupon['redemptions'] = 1;
                        $coupon['code'] = 'test-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

                        $shoppingCartPriceRule = $objectManager->create('MagentoSalesRuleModelRule');
                        $shoppingCartPriceRule->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)
                        ->setCouponCode($coupon['code'])
                        ->setUsesPerCoupon(NULL);
                        $shoppingCartPriceRule->save();





                        share|improve this answer




























                          0














                          Try code below



                          $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
                          $state = $objectManager->get('MagentoFrameworkAppState');
                          $state->setAreaCode('adminhtml');

                          $coupon['name'] = 'test';
                          $coupon['desc'] = 'Discount for Test';
                          $coupon['start'] = date('Y-m-d');
                          $coupon['end'] = '';
                          $coupon['max_redemptions'] = 1;
                          $coupon['discount_type'] = 'by_percent';
                          $coupon['discount_amount'] = 15;
                          $coupon['flag_is_free_shipping'] = 'no';
                          $coupon['redemptions'] = 1;
                          $coupon['code'] = 'test-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

                          $shoppingCartPriceRule = $objectManager->create('MagentoSalesRuleModelRule');
                          $shoppingCartPriceRule->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)
                          ->setCouponCode($coupon['code'])
                          ->setUsesPerCoupon(NULL);
                          $shoppingCartPriceRule->save();





                          share|improve this answer


























                            0












                            0








                            0







                            Try code below



                            $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
                            $state = $objectManager->get('MagentoFrameworkAppState');
                            $state->setAreaCode('adminhtml');

                            $coupon['name'] = 'test';
                            $coupon['desc'] = 'Discount for Test';
                            $coupon['start'] = date('Y-m-d');
                            $coupon['end'] = '';
                            $coupon['max_redemptions'] = 1;
                            $coupon['discount_type'] = 'by_percent';
                            $coupon['discount_amount'] = 15;
                            $coupon['flag_is_free_shipping'] = 'no';
                            $coupon['redemptions'] = 1;
                            $coupon['code'] = 'test-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

                            $shoppingCartPriceRule = $objectManager->create('MagentoSalesRuleModelRule');
                            $shoppingCartPriceRule->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)
                            ->setCouponCode($coupon['code'])
                            ->setUsesPerCoupon(NULL);
                            $shoppingCartPriceRule->save();





                            share|improve this answer













                            Try code below



                            $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
                            $state = $objectManager->get('MagentoFrameworkAppState');
                            $state->setAreaCode('adminhtml');

                            $coupon['name'] = 'test';
                            $coupon['desc'] = 'Discount for Test';
                            $coupon['start'] = date('Y-m-d');
                            $coupon['end'] = '';
                            $coupon['max_redemptions'] = 1;
                            $coupon['discount_type'] = 'by_percent';
                            $coupon['discount_amount'] = 15;
                            $coupon['flag_is_free_shipping'] = 'no';
                            $coupon['redemptions'] = 1;
                            $coupon['code'] = 'test-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

                            $shoppingCartPriceRule = $objectManager->create('MagentoSalesRuleModelRule');
                            $shoppingCartPriceRule->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)
                            ->setCouponCode($coupon['code'])
                            ->setUsesPerCoupon(NULL);
                            $shoppingCartPriceRule->save();






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 26 '18 at 1:28









                            Vu Tran KienVu Tran Kien

                            3521224




                            3521224






























                                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%2f131869%2fcreate-coupon-code-programmatically-in-magento-2-x%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

                                “%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

                                How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

                                變成蝙蝠會怎樣? 參考資料 外部連結 导航菜单Thomas Nagel, "What is it like to be a...