How To Redirect To Previous Page In Magento 2
Magento 2 CMS allows customization in order to improve the user experience.
The below post is a similar example that allows to redirect to previous page in Magento 2.
Now, a user filled a form on your store and clicked the submit button. The user’s data is saved in a file and you would want to display a message of a successful form submission or an error as per my earlier post to display error, success, & warning Message In Magento 2.
For that you need to redirect the user to the previous page URL and hence use this solution:
Method to redirect to previous page in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 |
namespace Company\Module\Controller\Index; use Magento\Framework\Controller\ResultFactory;class Actionname name extends \Magento\Framework\App\Action\Action { public function execute() { $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); // Your code $resultRedirect->setUrl($this->_redirect->getRefererUrl()); return $resultRedirect; } } |
Any doubts can be mentioned in the Comments section below. I’d be happy to help.
Feel free to share the solution with Magento community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
6 Comments
HI
I do not understand what this should be // Your code
It Should be Your Business Logic.
How to redirect from observer to cart page
Hello Sasikala,
You can try the below code:
$this->url is object of \Magento\Framework\UrlInterface
$this->responseFactory is object of \Magento\Framework\App\ResponseFactory
$redirectionUrl = $this->url->getUrl(‘checkout/cart/index’);
$this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();
Thank You
Hi
In which file path need to update this source…?
Hello Thomas,
You need to update this source in the Controller file path.
Thank you.