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
2 Answers
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 '';
}
}
-
Will be called every time when the user select the shipping method ? Commented Jun 8, 2018 at 15:26
-
I tried your solution but after using your code my checkout page become blank. Can you please add more details how it works ? Commented Jun 8, 2018 at 17:28
-
Do you use magento default checkout? It's working fine for M2.2.4. If you select shipping method in shipping page, then click next. In payment & review section will restrict your payment method. Commented Jun 8, 2018 at 17:39
-
-
I found the solution here magento.stackexchange.com/questions/108594/… and this worked for me perfectly. Commented Jun 10, 2018 at 12:18
I am not sure if magento has any event which triggers when the shipping method is selected.
One solution is to create plugin on saveAddressInformation
function of Magento\Checkout\Model\ShippingInformationManagement
and use after
method inside which you can implement your logic.