Magento – Magento 2: Which event get called when selecting shipping method on checkout

event-observermagento2

I build a custom shipping method and i want to hide "cash on delivery" payment method based on my shipping method selection. I am assuming that one possible way to write the code in observer and set the "is_available"= false for that payment method. But i am not sure whether is there any event get called when user choose the shipping method on checkout

Best Answer

SR/Stackexchange/etc/di.xml


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Payment\Model\MethodList">
        <plugin name="cashondeliveryplugin_frontend" type="SR\Stackexchange\Plugin\Model\MethodList" sortOrder="10"/>
    </type>
</config>

SR/Stackexchange/Plugin/Model/MethodList.php


namespace SR\Stackexchange\Plugin\Model;

class MethodList
{
    public function afterGetAvailableMethods(
        \Magento\Payment\Model\MethodList $subject,
        $availableMethods,
        \Magento\Quote\Api\Data\CartInterface $quote = null
    ) {
        $shippingMethod = $this->getShippingMethod($quote);
        foreach ($availableMethods as $key => $method) {
            // change logic here
            if(($method->getCode() == 'cashondelivery') && ($shippingMethod == 'flatrate_flatrate')) {
                unset($availableMethods[$key]);
            }
        }

        return $availableMethods;
    }

    /**
     * @param \Magento\Quote\Api\Data\CartInterface $quote
     * @return string
     */
    private function getShippingMethod($quote)
    {
        if($quote) {
            return $quote->getShippingAddress()->getShippingMethod();
        }

        return '';
    }
}
Related Topic