How to disable the Cash on Delivery payment method in backend and frontend Programmatically?
Here the code I'm using:
etc/di.xml
<type name="Magento\OfflinePayments\Model\Cashondelivery">
<plugin name="cashondeliveryplugin" type="Xxx\Yyy\Plugin\Model\Cashondelivery" sortOrder="10" disabled="false" />
</type>
Plugin:
public function aroundIsAvailable(
\Magento\OfflinePayments\Model\Cashondelivery $subject,
callable $proceed,
$quote = null
) {
$result = $proceed($quote);
$codAvailability = $this->_pincodeModel->isCODAvailable($quote->getShippingAddress()->getPostcode()) ? "yes" : "no";
if ($codAvailability == 'no') {
return false;
}
return $result;
}
The actual problem is: the quote is missed when plugin called from the frontend (checkout page).
Best Answer
You can use a simple plugin on the method
isAvailable
of the modelMagento\OfflinePayments\Model\Cashondelivery
:Just change the conditions to desired one.
The result on the frontend (checkout page):
The result on the backend (create new order page):
Full plugin could be found on github
Updated code:
Do not forget add your classes to the di (
_pincodeModel
).Update 2:
On the frontend the
$quote
argument is null because it was called from the method\Magento\OfflinePayments\Model\InstructionsConfigProvider::getConfig()
where the methodisAvailable()
of the each payment method was called without providing arguments, what means the$quote
will be null:But in the checkout session, it exists, and we can access it from the checkout session object.
Update 3:
For the backend the method
isAvailable()
of the all payment methods was called from theMagento\Payment\Block\Form\Container::getMethods()
method which provides a quote in the arguments list:Here is why you can access the quote object from the backend directly, and can not do that on the frontend.