1

Already add my custom module to Disable Payment method on the Checkout Page based on Product Attribute in Magento 2

Now I want to show the message to customer on Checkout Page if COD is Inactive by this code. Something like this

COD is not Available on Product - {Product Name}

app\code\Vendor\DisableCOD\Observer\DisablePaymentMethods.php
<?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()=="phoenix_cashondelivery")
                    {
                        $checkResult = $observer->getEvent()->getResult();
                        $checkResult->setData('is_available', false); 
                    }
                }

            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.