Question

Hello I want to hide "Cash on Delivery" Payment method when i select the Flat Rate Shipping Method in magento2 , already try another solution but it not work, please help me how can i achieve this thing?

Was it helpful?

Solution

I think the easiest way is to make a plugin for the method canUseCheckout in the Cashondelivery offline payment method.

app/code/StackExchange/HideFlatrate/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\OfflinePayments\Model\Cashondelivery">
        <plugin name="hide_cash_on_delivery_for_flatrate"
                type="StackExchange\HideFlatrate\Plugin\HideCashOnDeliveryForFlatrate"
        />
    </type>
</config>

app/code/StackExchange/HideFlatrate/Plugin/HideCashOnDeliveryForFlatrate.php

<?php
declare(strict_types=1);

namespace StackExchange\HideFlatrate\Plugin;

use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\OfflinePayments\Model\Cashondelivery;

class HideCashOnDeliveryForFlatrate
{
    /**
     * @var CheckoutSession
     */
    private CheckoutSession $checkoutSession;

    public function __construct(
        CheckoutSession $checkoutSession
    ) {
        $this->checkoutSession = $checkoutSession;
    }


    public function afterCanUseCheckout(Cashondelivery $cashondelivery, $result)
    {
        $quote = $this->checkoutSession->getQuote();

        $shippingMethod = $quote->getShippingAddress()->getShippingMethod();
        if ($shippingMethod === 'flatrate_flatrate') {
            return false;
        }
        return $result;
    }
}

The code above works and is tested. Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top