0

Hi i'm trying to hide a payment method if the company field is filled. I did find a solution but it's for Magento 1 (see link below). Does anyone know how i would do this in Magento 2? I'm working in Magento 2.3.4 if that's relevant.

M1 solution: Hide payment method if company name field got a value

If i look on stackexchange there are some solutions for hiding a payment method (Magento 2: Hide payment methods depends on shipping method) but i'm not sure how to get the company name data in there?

1
  • which company field? in shipping form or another
    – Devidas
    May 18 '20 at 16:29
0

create below files in your custom module.

The below example is used to hide the cash on delivery payment method

You can create an observer for the event payment_method_is_active

Vendor/Module/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="payment_method_is_active">
        <observer name="custom_payment" instance="Vendor\Module\Observer\PaymentMethodAvailable" />
    </event>
</config>

Vendor/Module/Observer/PaymentMethodAvailable.php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use \Magento\Checkout\Model\Cart;

class PaymentMethodAvailable implements ObserverInterface
{

protected $cart;
protected $logger;

public function __construct(
    Cart $cart,
    \Psr\Log\LoggerInterface $logger
  ){
    $this->cart = $cart;
    $this->logger = $logger;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
    //shipping company field
    $shippingCompanyField = $this->cart->getQuote()->getShippingAddress()->getCompany();

    //Billing company field
    $billingCompanyField = $this->cart->getQuote()->getBillingAddress()->getCompany();

    $paymentMethod = $observer->getEvent()->getMethodInstance()->getCode();

    if ($shippingCompanyField != '') {
      if ($paymentMethod == "cashondelivery") {
        $checkResult = $observer->getEvent()->getResult();
        $checkResult->setData('is_available', false);
    }
    }

}
}

I just check shippingCompanyField is filled or not. you can also check the billing company field then you can check another condition.

I hope this will help you.

1
  • It works but, if i got to the checkout and add company and go to payment so the field is there. And then go back a step and remove company so the field is gone but it was already selected then payment provider crashes because the selected method is gone now. Any idea? I tried googling on deselecting payment methods but no results.
    – Sanne
    Jun 8 '20 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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