我想阻止特定客户群购买不超过两种产品。我还需要阻止他们购物车中的特定数量。 如果是的话,这可能吗?那么执行该观察者、插件或偏好的最佳方法是什么? 如果有人以前做过,请分享您的解决方案。
我尝试通过插件停止添加到购物车来完成此操作,但页面重新加载,我无法显示异常消息。
<?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();
}
}
//di.xml file
<?xml version="1.0" encoding="utf-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Quote\Model\Quote">
<plugin name="limit_cart_items_plugin_name" type="YourVendor\YourModule\Plugin\Quote\ClassName" sortOrder="10" disabled="false"/>
</type>
</config>
//YourVendor\YourModule\Plugin\Quote
<?php
namespace YourVendor\YourModule\Plugin\Quote;
use Magento\Quote\Model\Quote;
use Magento\Framework\Exception\LocalizedException;
class ClassName
{
public function beforeBeforeSave(Quote $subject)
{
$customerGroupId = $subject->getCustomerGroupId();
// Define the customer group(s) you want to restrict
$restrictedCustomerGroups = [1, 3];
// Check if the customer group is in the restricted list
if (in_array($customerGroupId, $restrictedCustomerGroups)) {
// Get the items in the cart
$items = $subject->getAllItems();
// Define the maximum number of items allowed in the cart
$maxItemsAllowed = 2;
// Define the maximum cart total amount and here get specific amount
$maxCartTotal = 120;
$totalQty = 0;
$cartTotal = 0;
$itemsToRemove = [];
foreach ($items as $item) {
$totalQty += $item->getQty();
$cartTotal += $item->getRowTotal();
// Check if the item quantity exceeds the limit
if ($item->getQty() > $maxItemsAllowed) {
$itemsToRemove[] = $item;
}
}
// Check if the cart exceeds the limits
if ($totalQty > $maxItemsAllowed || $cartTotal > $maxCartTotal) {
// Remove extra items
foreach ($itemsToRemove as $itemToRemove) {
$subject->removeItem($itemToRemove->getId());
}
throw new LocalizedException(__('You can only add up to 2 products to your cart. and maximum amount 120.'));
}
}
return [$subject];
}
}