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

Geography at the pixel level

Shouldn't "much" here be used instead of "more"?

How to notate time signature switching consistently every measure

What did it mean to "align" a radio?

Is this app Icon Browser Safe/Legit?

Is there a symbol for a right arrow with a square in the middle?

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?

Do these rules for Critical Successes and Critical Failures seem Fair?

What is the accessibility of a package's `Private` context variables?

If a Druid sees an animal’s corpse, can they wild shape into that animal?

Can one be advised by a professor who is very far away?

Am I thawing this London Broil safely?

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

Origin of "cooter" meaning "vagina"

What does "fetching by region is not available for SAM files" means?

How to save as into a customized destination on macOS?

How to manage monthly salary

Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?

Loose spokes after only a few rides

Why do UK politicians seemingly ignore opinion polls on Brexit?

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

Should I use my personal e-mail address, or my workplace one, when registering to external websites for work purposes?

Worn-tile Scrabble

Is there any way to tell whether the shot is going to hit you or not?



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 11 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 11 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 11 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 11 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

                                Disable / Remove link to Product Items in Cart Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How can I limit products that can be bought / added to cart?Remove item from cartHide “Add to Cart” button if specific products are already in cart“Prettifying” the custom options in cart pageCreate link in cart sidebar to view all added items After limit reachedLink products together in checkout/cartHow to Get product from cart and add it againHide action-edit on cart page if simple productRemoving Cart items - ObserverRemove wishlist items when added to cart

                                Helsingin valtaus Sisällysluettelo Taustaa | Yleistä sotatoimista | Osapuolet | Taistelut Helsingin ympäristössä | Punaisten antautumissuunnitelma | Taistelujen kulku Helsingissä | Valtauksen jälkeen | Tappiot | Muistaminen | Kirjallisuutta | Lähteet | Aiheesta muualla | NavigointivalikkoTeoksen verkkoversioTeoksen verkkoversioGoogle BooksSisällissota Helsingissä päättyi tasan 95 vuotta sittenSaksalaisten ylivoima jyräsi punaisen HelsinginSuomalaiset kuvaavat sotien jälkiä kaupungeissa – katso kuvat ja tarinat tutuilta kulmiltaHelsingin valtaus 90 vuotta sittenSaksalaiset valtasivat HelsinginHyökkäys HelsinkiinHelsingin valtaus 12.–13.4. 1918Saksalaiset käyttivät ihmiskilpiä Helsingin valtauksessa 1918Teoksen verkkoversioTeoksen verkkoversioSaksalaiset hyökkäävät Etelä-SuomeenTaistelut LeppävaarassaSotilaat ja taistelutLeppävaara 1918 huhtikuussa. KapinatarinaHelsingin taistelut 1918Saksalaisten voitonparaati HelsingissäHelsingin valtausta juhlittiinSaksalaisten Helsinki vuonna 1918Helsingin taistelussa kaatuneet valkokaartilaisetHelsinkiin haudatut taisteluissa kaatuneet punaiset12.4.1918 Helsingin valtauksessa saksalaiset apujoukot vapauttavat kaupunginVapaussodan muistomerkkejä Helsingissä ja pääkaupunkiseudullaCrescendo / Vuoden 1918 Kansalaissodan uhrien muistomerkkim

                                Adjektiivitarina Tarinan tekeminen | Esimerkki: ennen | Esimerkki: jälkeen | Navigointivalikko