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
<?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>
view raw di.xml hosted with ❤ by GitHub


Vendor_Module\Model\Checkout\Cart\AddProduct.php
<?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];
}
}
view raw AddProduct.php hosted with ❤ by GitHub




Comments

Popular posts from this blog

SEO for your Press Releases [Updated 2025 list]

XDebug - PHPStorm - Mac: How to configure Xdebug with PHPStorm on Mac OS and PHP 7.3