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:

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;
    }
}

That’s it.

Feel free to share the solution with Magento community via social media.

Thank you.

Table of Contents