cancel
Showing results for 
Search instead for 
Did you mean: 

How to remove COD payment method using a product attribute?

How to remove COD payment method using a product attribute?

I want to hide COD payment method based on the Product attribute. I tried payment_method_is_active event method to disable using observer like below.

My observer file is here

public function execute( \Magento\Framework\Event\Observer $observer ) {

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

$method = $observer->getEvent()->getMethodInstance();

$quote = $observer->getEvent()->getQuote(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart');

$items = $cart->getItems();

$disable_cod = false;

foreach ($items as $item) {

$options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()); if(array_key_exists("attributes_info",$options) && count($options['attributes_info']) >= 1) {

foreach($options['attributes_info'] as $myopt) {

if($myopt['label']==='E-Gift'){ // Condition i am checking

$disable_cod = true; } } }

if($disable_cod){

$this->logger->critical("Disable COD");

if($method->getCode() === 'cashondelivery'){

$this->logger->critical("Here 1");

$result = $observer->getEvent()->getResult();

$result->setData('is_available', false); }

}else{ $this->logger->critical("Enable COD");

} }

COD is disabling only if I have an E-Gift product only. If I have other products with E-Gift product COD is not disabling. Ultimately I need to hide the COD if at least one product including E-Gift. Please help me with this.