系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
在Magento 2中显示特定类别的付款方式的步骤:
步骤1:首先,在 以下文件路径的etc文件夹中创建一个事件.xml文件
app\code\Vendor\Extension\etc
现在添加代码,如下所述。
<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="payment_method_is_active" instance="Vendor\Extension\Observer\ActivePaymentMethod" /> </event> </config>
步骤2:在第二步中,在 模型文件夹中创建ActivePaymentMethod.php文件,路径如下
app\code\Vendor\Extension\Observer
然后添加代码,如下所示。
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Catalog\Api\ProductRepositoryInterface; class ActivePaymentMethod implements ObserverInterface { protected $_cart; protected $_checkoutSession; protected $productRepository; public function __construct( \Magento\Checkout\Model\Cart $cart, \Magento\Checkout\Model\Session $checkoutSession, ProductRepositoryInterface $productRepository ) { $this->_cart = $cart; $this->_checkoutSession = $checkoutSession; $this->productRepository = $productRepository; } /** * Execute observer * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $quote = $this->getCheckoutSession()->getQuote(); $categoryID = "Add your category ID"; $items = $quote->getAllItems(); $flag = false; foreach($items as $item) { $product = $this->getProduct($item->getProductId()); $categoryIds = $product->getCategoryIds(); if(in_array($categoryID, $categoryIds)) { $flag = true; break; } } if($flag == false && $observer->getEvent()->getMethodInstance()->getCode()=="Enter Your Payment Method Code") { $checkResult = $observer->getEvent()->getResult(); $checkResult->setData('is_available', false); } } public function getProduct($productId) { return $product = $this->productRepository->getById($productId); } public function getCart() { return $this->_cart; } public function getCheckoutSession() { return $this->_checkoutSession; } }
结论:
这样,您可以在Magento 2中显示特定类别的付款方式。