I am using magento 2. And I need to disable one payment method 'cash on delivery' to specific cities(not for countries).I found so many solutions but those are not meant for magento 2, I think those are for older versions.Because I couldn't find those files(or methods in the specified location) in my code. Can anyone help me ? Any help will be appreciated.
You need to create a new module and use a 'plugin' to add some logic to the isAvailable
method of Magento\OfflinePayments\Model\Cashondelivery
.
Example plugin class:
<?php
namespace Your\Module\Plugin;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Model\Quote;
class CashondeliveryPlug
{
public function aroundIsAvailable(AbstractMethod $subject, callable $proceed, Quote $quote)
{
$result = $proceed($quote);
if ($result) {
$city = $quote->getBillingAddress()->getCity();
if (in_array(strtolower($city), self::$cities)) return false;
}
return $result;
}
static $cities = [ // the cities to be excluded
'austin',
'new york',
'boston'
];
}
And you'd have this in {module_dir}/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="cashondeliveryplug" type="Your\Module\Plugin\CashondeliveryPlug" disabled="false" sortOrder="10"/>
</type>
</config>
-
-
In my project there is no isAvailable function in cashondelivery.php file.but instead this function is situated in AbstractMethod.php file – Anu Dec 17 '16 at 12:18
-
1Yes,
Cashondelivery
inherits the method fromAbstractMethod
. You should follow a tutorial on how to create a module and use this code in your module. The only files I haven't given you areregistration.php
andetc/module.xml
which are the boilerplate module declaration files. – Aaron Allen Dec 17 '16 at 12:24 -
thanks Aaron. And i'm really new to magento. Can you plz guide me to place this code, if you don't mind? – Anu Dec 17 '16 at 12:29
-
1There's plenty of good tutorials explaining how to create a module (inchoo.net/magento-2/how-to-create-a-basic-module-in-magento-2) - do that first. Assuming you have a module, you'd then put the code in
{your_module}/Plugin/CashondeliveryPlug.php
and{your_module}/etc/di.xml}
. – Aaron Allen Dec 17 '16 at 12:36