Magento2 – How to Redirect from Observer to CMS Page

cms-pagesevent-observermagento-2.1magento2redirect

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

protected $responseFactory;
protected $url;

public function __construct(
    ...
    \Magento\Framework\App\ResponseFactory $responseFactory,
    \Magento\Framework\UrlInterface $url
    ...
) {
    $this->responseFactory = $responseFactory;
    $this->redirect = $redirect;
    $this->url = $url;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
    //... Your Code

    $customRedirectionUrl = $this->url->getUrl('my-cms-page'); //Get url of cms page
    $this->responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse(); //Redirect to cms page
    die(); //This will stop execution and redirect to specific page
}
Related Topic