I have a requirement to prevent a user from adding a product when a certain condition is not met. I created a beforeAddProduct plugin. At the beginning of the plugin i have this code:
if(!$condition){
throw new LocalizedException(__('You can't add this product to cart'));
}
Of-course this plugin will be executed anytime a user tries to add a product to cart. When a user is in product catalog, and tries to add a product without viewing it,just like below.
the exception will be thrown and magento will redirect to view product. And it will display the message of the exception. What i want is to have the error message displayed without redirect or refresh. The same behaviour when the add product to cart was successful. If i view the product and afterwards add that product to cart, if the plugin i created throws an exception, the page will refresh or reload and the error message will be displayed again. I do not want this refresh nor reload.
Upon interogating through debugging, i saw the catalog-add-to-cart.js which is the file that causes the redirect.
The exception will cause the redirect. Ironically, the success of the ajax will get called, one would except since an error was thrown, the error function will get called.