In Magento 2, You can redirect to any link or forcefully redirect to any link by Magento\Framework\Controller\Result\RedirectFactory object.
You can redirect from plugin or controller file to any link on the site by setPath() or setUrl() function.
Using setUrl($url) -> You need to pass link as parameter for redirect
Using setPath($path) -> You need to pass path(action URL) as parameter
1 2 3 4 5 | public function __construct( \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory ) { $this->resultRedirectFactory = $resultRedirectFactory; } |
/* Using Direct path, you need to pass action URL in a setPath() method */
For redirect to cart page, Pass action path as checkout/cart,
For Redirect to contact page,a parameter is contact
For Redirect to a login page, a parameter is customer/account/login
1 2 3 | $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('checkout/cart'); return $resultRedirect; |
Pass Query string using above function by below methods,
1 2 3 4 | $argument = ['id' => $getId, '_current' => true]; $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('checkout/cart',$argument); return $resultRedirect; |
You can redirect to any link by direct URL using below way,
1 2 3 4 | $resultRedirect = $this->resultRedirectFactory->create(); $url = 'http://127.0.0.1/magento2/checkout/cart'; $resultRedirect->setUrl($url); return $resultRedirect; |
You need to pass Direct URL for a redirect to a specific link in Magento 2.