1

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?

1 Answer 1

1

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!

1
  • Yes Brother its working Thank you @Kristoffer Commented Oct 29, 2020 at 6:58

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.