Magento2: How to stop a product from getting added to cart programmatically?
If youn want to stop a product from getting addded to cart programmatically, add below files to your module:
Vendor_Module\etc\di.xml
Vendor_Module\Model\Checkout\Cart\AddProduct.php
Vendor_Module\etc\di.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0"?>
<!--
/**
* @author Reena Parekh <reena1.parekh@gmail.com>
*/
-->
<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 name="interceptAddingProductToCart"
type="Vendor\Module\Model\Checkout\Cart\AddProduct"
sortOrder="10"
disabled="false" />
</type>
</config>
Vendor_Module\Model\Checkout\Cart\AddProduct.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php
/**
* @author Reena Parekh <reena1.parekh@gmail.com>
*/
namespace Vendor\Module\Model\Checkout\Cart;
use Magento\Framework\Exception\LocalizedException;
/**
* Class AddProduct
*/
class AddProduct
{
/**
* @var \Magento\Quote\Model\Quote
*/
protected $quote;
/**
* Plugin constructor.
*
* @param \Magento\Checkout\Model\Session $checkoutSession
*/
public function __construct(
\Magento\Checkout\Model\Session $checkoutSession
) {
$this->quote = $checkoutSession->getQuote();
}
/**
* beforeAddProduct
*
* @param $subject
* @param $productInfo
* @param null $requestInfo
*
* @return array
* @throws LocalizedException
*/
public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
{
if ($this->quote->hasData('custom_attribute')) {
throw new LocalizedException(__('Could not add Product to Cart'));
}
return [$productInfo, $requestInfo];
}
}
Comments
Post a Comment