What I want to do is if my custom attribute is set in quote then i do not want any product to be added in cart. My custom attribute is being set correctly.
To stop product from getting added to cart, I have written an Observer which observes this event controller_action_predispatch_checkout_cart_add
My observer file code:
public function execute(\Magento\Framework\Event\Observer $observer) {
$addedItemId = $observer->getRequest()->getParam('product');
$quote = $this->_cart->getQuote();
if(!empty($quote)) {
$customAttribute = $quote->getData('custom_attribute');
if(!empty($customAttribute)) {
$controller = $observer->getControllerAction();
$storeId = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
$product = $this->_productRepository->getById($addedItemId, false, $storeId);
$observer->getRequest()->setParam('product', null);
$this->_messageManager->addError(__('This product cannot be added to your cart.'));
echo false;
$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'checkout/cart/index');
}
}
}
With this code, I am able not able to stop the add to cart process.
So as per this answer of Magento1 - https://stackoverflow.com/questions/14190358/stop-add-to-cart-and-supply-message-to-user-in-magento . I tried replacing
$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'checkout/cart/index');
with (This is not the best way of doing it. If there is any better way, please suggest)
header("Location: " . $product->getProductUrl());
die();
This ultimately stops the add to cart process but the add to cart button still keeps on showing "Adding". How can i perform this correctly so that add to cart button goes back to its previous state and the product too does not get added to cart ?