Assuming you named Magetu
as the vendor name, EngravingServices
as the module name, and your custom product attribute named engraving_services
.
Declare a new observer in events.xml
, and use payment_method_is_active
event
File path: app/code/Magetu/EngravingServices/etc/events.xml
<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="disable_cashondelivery_for_engraving_services_product" instance="MageTu\EngravingServices\Observer\DisableCashondeliveryForEngravingServicesProduct" />
</event>
</config>
Create the Observer class
File path: app/code/Magetu/EngravingServices/Observer/DisableCashondeliveryForEngravingServicesProduct.php
<?php
declare(strict_types=1);
namespace Magetu\EngravingServices\Observer;
use Magento\Framework\DataObject;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\OfflinePayments\Model\Cashondelivery;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Api\Data\CartInterface;
class DisableCashondeliveryForEngravingServicesProduct implements ObserverInterface
{
/**
* Disable Cash On Delivery payment method if the cart contains Engraving Services product
*
* @param Observer $observer
* @throws LocalizedException
*/
public function execute(Observer $observer)
{
/** @var CartInterface $quote */
$quote = $observer->getQuote();
if (!$quote) {
return;
}
/** @var DataObject $result */
$result = $observer->getResult();
/** @var AbstractMethod $methodInstance */
$methodInstance = $observer->getMethodInstance();
$paymentCode = $methodInstance->getCode();
if ($paymentCode === Cashondelivery::PAYMENT_METHOD_CASHONDELIVERY_CODE) {
$allItems = $quote->getAllItems();
/** @var $item \Magento\Quote\Model\Quote\Item */
foreach ($allItems as $item) {
if ($item->getProduct()->getData('engraving_services')) {
$result->setData('is_available', false);
break;
}
}
}
}
}