4

I want to generate coupon on order success below is the code i am unsing to generate in Observer

public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\SalesRule\Model\Rule $rule
    )
    {
        $this->logger = $logger;
        $this->rule = $rule;        
    }    
public function execute(\Magento\Framework\Event\Observer $observer)
        {
            $order = $observer->getEvent()->getOrder();
            $orderId = $order->getId();
            $coupon = [];
            $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 =  $this->rule->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();

        }

events.xml

<event name="sales_order_save_after">
        <observer name="vendor_coupon_order_save_after" instance="Vendor\Coupon\Observer\GiftcardSave" />
    </event>
2
  • What is the problem? is this event not firing?
    – Amit Bera
    Jun 25, 2019 at 10:50
  • payment info message show Invalid method Magento\\SalesRule\\Model\\Rule::create Jun 25, 2019 at 10:57

1 Answer 1

1

Change

Magento\SalesRule\Model\Rule

to

Magento\SalesRule\Model\RuleFactory

And change

 $this->rule->create('Magento\SalesRule\Model\Rule')

to

 $this->rule->create()

If you want to use Service contact then check out the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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