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:
<?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 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.