Showing results for 
Search instead for 
Did you mean: 

Apply custom promo rule using observer in Magento 2

Apply custom promo rule using observer in Magento 2

I have created new table in Magento 2, for storing custom promorules, now I have created observer for event controller_action_predispatch_checkout_cart_couponPost and inside that observer I want to check if user has entered any custom rule then apply discount according to that rule.

Below is my code:



namespace Webkul\Grid\Observer; use Magento\Framework\Event\ObserverInterface; class coupenAppliedAfter implements ObserverInterface { /** * @var ObjectManagerInterface */ protected $_objectManager; /** * @param \Magento\Framework\ObjectManagerInterface $objectManager */ public function __construct( \Magento\Framework\ObjectManagerInterface $objectManager ) { $this->_objectManager = $objectManager; } /** * customer register event handler * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { // get enetered coupen code
= $observer->getControllerAction();
= $controller->getRequest()->getParam('coupon_code');
= \Magento\Framework\App\ObjectManager::getInstance();
= $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); // get list of coupon codes from that custom table
= $connection->fetchAll("SELECT * FROM custom_promotion_rules"); foreach($all_custom_codes as $code) {
= $code['code']; // matching if user has entered any custom code if($couponCode == $db_coupen_code) {
// if yes trying to apply custom discount
= $code['discount_amount'];
= $observer->getEvent()->getResult();
->setBaseAmount($DiscountAmount); } } } }

but above code is not working and giving error Fatal error: Uncaught Error: Call to a member function setAmount() on null

Please suggest solution for this.