3

I need to disable the CoD payment method for carts with downloadable products. I started working on a plugin, but got hung up on this - have no idea how to get product types from cart.

Any ideas?

1

2 Answers 2

5

Best idea to use event/observer concept.

Fire an observer on event: payment_method_is_active.

Observer:

<?php
namespace [Vendorname]\[Modulename]]\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;

class ObserverforDisabledCod implements ObserverInterface
{
    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $result = $observer->getEvent()->getResult();
        $method_instance = $observer->getEvent()->getMethodInstance();
        $quote = $observer->getEvent()->getQuote();

        if ($quote === null || $method_instance->getCode() != 'cashondelivery')
            return;

        /* Disable All payment gateway exclude Your payment Gateway */
        $items = $quote->getAllVisibleItems();
        foreach ($items as $eachitem) {
            if ($eachitem->getProductType() == 'downloadable') {
                $result->setData('is_available', false);
                break;
            }
        }

    }
}
5
  • Thank you so much Amit! Any ideas on disabling CoD for select shipping methods? :) Jan 11, 2017 at 10:24
  • ya.. it possaible. you already get quote object at this observer then you can get selected ship,ment
    – Amit Bera
    Jan 11, 2017 at 10:33
  • I need getShippingMethod(). How to get it?
    – Gediminas
    Sep 27, 2017 at 11:30
  • I found the solution here magento.stackexchange.com/a/189530/46716
    – Gediminas
    Sep 27, 2017 at 13:09
  • cool, .........
    – Amit Bera
    Sep 27, 2017 at 13:17
2

Didn't work for me, needed to make the following changes:

  1. Replaced $result->isAvailable = false; with $result->setData('is_available', false);
  2. Replaced $items= as $eachitem with $items as $eachitem

(magento 2.1.7)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.