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

Landlord wants to switch my lease to a "Land contract" to "get back at the city"

A poker game description that does not feel gimmicky

Is bread bad for ducks?

FPGA - DIY Programming

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

Can you compress metal and what would be the consequences?

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

How to type this arrow in math mode?

Geography at the pixel level

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Apparent duplicates between Haynes service instructions and MOT

Loose spokes after only a few rides

Can a flute soloist sit?

Are children permitted to help build the Beis Hamikdash?

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

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

Identify boardgame from Big movie

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

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

Did 3000BC Egyptians use meteoric iron weapons?

Is three citations per paragraph excessive for undergraduate research paper?

Where to refill my bottle in India?

How to save as into a customized destination on macOS?

What tool would a Roman-age civilization have for the breaking of silver and other metals into dust?



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

                                Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

                                Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

                                How to solve knockout JS error in Magento 2 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?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2