当前位置: 技术文章>> 如何防止在Magento 2中多次将同一产品添加到购物车

文章标题:如何防止在Magento 2中多次将同一产品添加到购物车
  • 文章分类: Magento
  • 17938 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


防止在Magento 2中多次将同一产品添加到购物车的步骤:

步骤1:首先,转到以下路径

app\code\Vendor\Extension\etc\di.xml

并添加代码如下

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <type name="Magento\Checkout\Model\Cart">
     <plugin disabled="false" name="Vendor_Extension_Plugin_Magento_Checkout_Cart_BeforeAddToCartProduct" type="Vendor\Extension\Plugin\Magento\Checkout\Cart\BeforeAddToCartProduct"/>
 </type>
</config>

步骤2:现在,移至以下路径

app\code\Vendor\Extension\Plugin\Magento\Checkout\Cart\BeforeAddToCart.php

并添加下面提到的代码

<?php
    declare(strict_types=1);
   
namespace Vendor\Extension\Plugin\Magento\Checkout\Cart;
 
use Magento\Checkout\Model\Cart;
use Magento\Checkout\Model\Session;
use Magento\Catalog\Model\Product;
use Magento\Checkout\Model\Session\Proxy as SessionProxy;
use Magento\Framework\Message\ManagerInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\UrlInterface;
 
class BeforeAddToCartProduct
{
 
    private $messageManager;
    private $cartSession;
    private $configurableProduct;
    private $url;
    private $session;
 
    public function __construct(
        Configurable $configurableProduct,
        ManagerInterface $messageManager,
        SessionProxy $cartSession,
        UrlInterface $url,
        Session $session)
   {
        $this->messageManager = $messageManager;
        $this->cartSession = $cartSession;
        $this->configurableProduct = $configurableProduct;
        $this->url = $url;
        $this->session = $session;
    }
 
    public function beforeAddProduct(Cart $subject, $productInfo, $requestInfo=null)
    {
        $enableProductCartControl=true;
 
        $product = null;
        $parentProduct=null;
 
        if ($productInfo instanceof Product)
        {
            $product = $productInfo;
            if (!$product->getId())
            {
                throw new \Magento\Framework\Exception\LocalizedException(
                    __("This product wasn't found. Verify the product and try again.")
                );
            }
        }
 
        if ($product)
        {
            // For Simple Product
            if ($product->getTypeId()==='configurable')
            {
                if (isset($requestInfo['super_attribute']))
                {
                    $parentProduct=$product;
                    $childProduct = $this->configurableProduct->getProductByAttributes($requestInfo['super_attribute'] ,$product);
                    // change $product to child
                    $product=$childProduct;
                }
            }
            if ($product && $enableProductCartControl)
            {
                    // For check product is in cart or not
                    if($this->cartSession->getQuote()->hasProductId($product->getId()))
                    {
                        // Redirection to the cart page
                        $this->session->setRedirectUrl($this->url->getUrl('checkout/cart/index'));
                        throw new \Magento\Framework\Exception\LocalizedException(
                            __("[x] This product is already in the cart. Testing, testing : ". $product->getSku())
                        );
                    }
             }
        }
        return [$productInfo, $requestInfo];
    }
 
    /**
     * Get request for product add to cart procedure
     *
     * @param \Magento\Framework\DataObject|int|array $requestInfo
     * @return \Magento\Framework\DataObject
     * @throws \Magento\Framework\Exception\LocalizedException
     */
 
    private function _getProductRequest($requestInfo)
    {
        if ($requestInfo instanceof \Magento\Framework\DataObject)
        {
            $request = $requestInfo;
        }
        elseif (is_numeric($requestInfo))
        {
            $request = new \Magento\Framework\DataObject(['qty' => $requestInfo]);
        }
        elseif (is_array($requestInfo))
        {
            $request = new \Magento\Framework\DataObject($requestInfo);
        }
        else
        {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('We found an invalid request for adding product to quote.')
            );
        }
        return $request;
    }
}

结论:

因此,通过上述步骤,您可以防止在Magento 2中多次将同一产品添加到购物车。


推荐文章