I want to disable a cash on delivery payment method on the checkout for specific products I followed the code in this question
Disable Payment Method at Checkout in Magento 2 Based on Product Attribute
I modified the payment name in this file
Vendor/DisableCOD/Observer/DisablePaymentMethods.php
to cashondelivery
<?php
namespace Vendor\DisableCOD\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
class DisablePaymentMethods implements ObserverInterface
{
public function __construct(\Psr\Log\LoggerInterface $logger)
{
$this->_logger = $logger;
}
/**
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
// get cart items
$items = $cart->getItems();
// get attribute value of cart items
foreach ($items as $item)
{
$p = $objectManager->get('Magento\Catalog\Model\Product')->load($item['product_id']);
$attribute = $p->getResource()->getAttribute('cod');
if ($attribute)
{
$attr_value = $attribute ->getFrontend()->getValue($p);
if($attr_value == 'Yes' || $attr_value == 'yes' || $attr_value == 'YES')
{
if($observer->getEvent()->getMethodInstance()->getCode()=="cashondelivery")
{
$checkResult = $observer->getEvent()->getResult();
$checkResult->setData('is_available', false);
}
}
}
}
}
}
then I created new Product Attribute that named 'cod' with input type 'Yes/No' but nothing happened the cash on delivery method still enabled for
getAllItems()method was called on the line 33, not 34. Additionally, please confirm that you have properly applied an observer to thepayment_method_is_activeevent? You can reference the solution in the following post for guidance: https://magento.stackexchange.com/questions/364348/how-to-disable-cod-payment-method-based-on-product-attribute-value-in-magento-2. – Tu Van Sep 26 '23 at 15:35