Method to Redirect To Previous Page In Magento 2

How to Add Color Picker in Magento 2 Admin Configuration
December 15, 2020
August 8, 2023

Agree or you don’t agree, user Interface is a very vital factor in any user satisfaction in an online store. Navigation through pages should be smooth and easy.

Moving from one page to another page shouldn’t be cranky and tiring for the user. So, therefore, working on navigation is a must for Magento Developers.

Magento 2 CMS gives their user the power to customization in the aim of improving the user experience.This post teaches you the steps on how to redirect to the previous page in Magento 2. Some of the actions performed by user are the basic login procedures and registration steps and clicking on submit button. After the user clicks on the submit button, the form should be processed successfully without any error or any warming message displayed on screen.

For that you need to redirect the user to the previous page URL and hence guide them to following lines of code:


Method to redirect to previous page in Magento 2:

namespace [Vendor]\[Module]\Controller\Index;
use Magento\Framework\Controller\ResultFactory;

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

These are the lines of code to be implemented for redirecting to previous page under Magento 2.

Any doubts can be mentioned here and will be solved by us.

Thank you for reading our blog !

Related Posts