5

in a magento 2.2 based site we need to programmatically create a coupon code for . However was only able to find one code sample and it does not seem to work. Meaning no coupon code is created and when I look in the exception.log file I see the below error message

main.CRITICAL: Notice: Undefined property: Smartwave\Porto\Block\Template::$objectManager in /var/www/html/****.com/vendor/magento/framework/View/TemplateEngine/Php.php on line 110 {"exception":"[object] (Exception(code: 0):

Below is the code I am trying to use. Also as a side note the coupon code is created in the admin panel as a cart price rule.

//lets create a coupon code
$coupon['name'] = 'vip_signup';
$coupon['desc'] = 'Discount for vip signup.';
$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'] ='NL01-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes


$shoppingCartPriceRule = $this->objectManager->create('Magento\SalesRule\Model\Rule');

$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);

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

3 Answers 3

13
+50

Create CouponCode.php file at magento root and add below code in this file. After run this file in browser and check admin side.

<?php
use Magento\Framework\App\Bootstrap; 

/**
 * If your external file is in root folder
 */
require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
//$state->setAreaCode('frontend');
$state->setAreaCode('adminhtml');  


$coupon['name'] = 'vip_signup';
$coupon['desc'] = 'Discount for vip signup coupon.';
$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'] ='NL01-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

$shoppingCartPriceRule = $obj->create('Magento\SalesRule\Model\Rule');
$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();

OR

User below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$state = $objectManager->get('Magento\Framework\App\State');
//$state->setAreaCode('frontend');
$state->setAreaCode('adminhtml');  


$coupon['name'] = 'vip_signup';
$coupon['desc'] = 'Discount for vip signup coupon.';
$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'] ='NL01-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

$shoppingCartPriceRule = $objectManager->create('Magento\SalesRule\Model\Rule');
$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();
18
  • Thank you this works. How could this code be modified to just create a coupon code in an existing cart price rule?
    – Jayreis
    Commented Jan 3, 2018 at 15:42
  • Try this: $objectManager = $oldCouponCode = 'NL01-1234'; $newCouponCode = 'NL01-12345'; $couponModel = $obj->create('Magento\SalesRule\Model\Coupon')->load($oldCouponCode, 'code'); if($couponModel->getRuleId()) { $shoppingCartPriceRule = $obj->create('Magento\SalesRule\Model\Rule')->load($couponModel->getRuleId()); $shoppingCartPriceRule->setCouponCode($newCouponCode); $shoppingCartPriceRule->save(); }
    – Abdul
    Commented Jan 4, 2018 at 5:01
  • What if I have to create only for single product id.
    – urfusion
    Commented Mar 20, 2018 at 6:32
  • @urfusion Are you needed with coupon code or auto apply discount in single product?
    – Abdul
    Commented Mar 20, 2018 at 11:27
  • 1
    @AsadKhan : Please check the code dropbox.com/s/ml66zotfwtarxlu/CouponCode.php?dl=0
    – urfusion
    Commented Mar 30, 2019 at 6:37
0

I think you have not initialized $objectManager in your code, add following before using objectmanager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

or use dependency injection for the same.

0

Using below code, Cart coupon is generated for magento 2.2 and there are not any issue related to coupon code.

Coupon code is generated using below code fine,

please add before line with $objectmanager declaration,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

Your final code,

$coupon['name'] = 'vip_signup';
$coupon['desc'] = 'Discount for vip signup coupon.';
$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'] ='NL01-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$shoppingCartPriceRule = $objectManager->create('Magento\SalesRule\Model\Rule');

$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();

main.CRITICAL: Notice: Undefined property: Smartwave\Porto\Block\Template::$objectManager in /var/www/html/****.com/vendor/magento/framework/View/TemplateEngine/Php.php on line 110 {"exception":"[object] (Exception(code: 0):

For issue you faced is related to Your Porto Theme and not related to above coupon code so please verify your theme or might be check using default luma theme and just disable your current Porto Theme.

1
  • What if I have to create only for single product id.
    – urfusion
    Commented Mar 20, 2018 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.