I want to restrict some products from add to cart and redirect to a cms page on Add to Cart action. I have used 'controller_action_predispatch_checkout_cart_add' event.
The code restrict the add to cart action,but the redirection is not working.
Here is my code
namespace NamaSpace\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class RestrictAddToCart implements ObserverInterface
{
protected $_request;
protected $_product;
protected $_responseFactory;
protected $_url;
public function __construct(
RequestInterface $request,
\Magento\Catalog\Model\Product $product,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url
)
{
$this->_request = $request;
$this->_product = $product;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
}
/**
* add to cart event handler.
*
* @param \Magento\Framework\Event\Observer $observer
*
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$productId = $observer->getRequest()->getParam('product');
$product = $this->_product->load($productId);
if ($product->getPrescProduct()) {
$observer->getRequest()->setParam('product', false);
$customRedirectionUrl = $this->_url->getUrl('prescription-page');
$this->_responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse(); exit;
return $this;
}
return $this;
}
}
Best Answer