I created a new table in Magento 2 to store custom promorules, now I created an observer for the controller_action_predispatch_checkout_cart_couponPost event, and inside this observer I want to check if the user is entered in any custom rule, and then apply the discount according to this rule.
Below is my code:
<?php 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 $controller = $observer->getControllerAction(); $couponCode = $controller->getRequest()->getParam('coupon_code'); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); // get list of coupon codes from that custom table $all_custom_codes = $connection->fetchAll("SELECT * FROM custom_promotion_rules"); foreach($all_custom_codes as $code) { $db_coupen_code = $code['code']; // matching if user has entered any custom code if($couponCode == $db_coupen_code) { // if yes trying to apply custom discount $DiscountAmount = $code['discount_amount']; $result = $observer->getEvent()->getResult(); $result->setAmount($DiscountAmount); $result->setBaseAmount($DiscountAmount); } } } }
but the code above does not work and gives the error Fatal error: Uncaught Error: Call to a member function setAmount() on null
Please suggest a solution for this.
Dhara parmar
source share