我想阻止特定客户群购买不超过两种产品。我也需要停止他们在车的具体数额。这是可能的,如果是的话,那么什么是最好的方法来做观察者,插件或preference?如果有人以前做过,请分享你的解决方案。
我试图通过插件停止添加到购物车,但页面重新加载,我无法显示异常消息。
<?php
namespace CustomPlugin\CartProductRestriction\Plugin\Cart;
use Magento\Checkout\Controller\Cart\Add;
use Magento\Framework\Message\ManagerInterface;
use Magento\Checkout\Model\Cart;
class RestrictCartQty
{
protected $customerSession;
protected $messageManager;
protected $cart;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
ManagerInterface $messageManager,
Cart $cart
) {
$this->customerSession = $customerSession;
$this->messageManager = $messageManager;
$this->cart = $cart;
}
public function aroundExecute(Add $subject, callable $proceed)
{
$allowedCustomerGroup = 4;
$customerGroupId = $this->customerSession->getCustomer()->getGroupId();
if ($customerGroupId == $allowedCustomerGroup) {
$itemCount = $this->cart->getQuote()->getItemsQty();
if ($itemCount >= 2) {
$message = __('You can only add 2 items to your cart.');
$this->messageManager->addError($message);
return $subject;
}
}
return $proceed();
}
}
1条答案
按热度按时间jgzswidk1#