Blog

Method To Redirect To Previous Page In Magento 2

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:

Example 1 :

<?php

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.

Example 2:

The path of this interface which is used for fetching the Referrer URL is given below.

Path is Magento\Framework\App\Response\RedirectInterface.

In case of PHP you can use simple code which given below to get referral url.

$_SERVER["HTTP_REFERER"].

But in case of Magento, the best way is to just call the interface in __construct() function and fetch the referrer URL.

Below is code snippet to referral Url.

public function __construct( 
       \Magento\Framework\App\Response\RedirectInterface $redirect
) { 
     $this->redirect = $redirect;
}

In function, then you can call below line to get referrer Url.

Use the below code for it.

echo $this->redirect->getRefererUrl();
echo $this->redirect->getRedirectUrl();

Magento 2 get Referrer Url in Controller

It is simple to get referer url in controller.

To achieve this you have to use the RedirectInterface.

You can refer the above code which is used in the construct function.

Check with the below code get the referrer url in your execute method like this.

$redirectUrl = $this->redirect->getRedirectUrl();

Leave a Reply

Your email address will not be published. Required fields are marked *

🚀 Let’s Connect on LinkedIn! 🚀

Want to level up your skills and knowledge? 🚀
Follow us on LinkedIn to get:
✅ Expert insights on business growth
✅ Daily tips to sharpen your skills
✅ Exclusive updates from The Coach SMB

Let's grow together!