Magento2 – URL Redirections and URL Builder

In this blog, we will learn different types of url redirection to be used in magento2. Basically, we use two types of redirection:

  1. to previous page
  2. to any other URL

Well, let’s start with the first one. To redirect to previous page from my custom action in magento2, we need to add use following block of code in our controller:

namespace Excellence\Hello\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);
           $resultRedirect->setUrl($this->_redirect->getRefererUrl());
           return $resultRedirect;
      }
}

Here, we are first creating instance of ResultFactory by calling create()and then by using it we are redirecting to another URL using setURL() method. In the setUrl() method, we pass the desired URL. Here we wand to redirect the action to previous page, so we are passing $this->_redirect->getRefererUrl() as parameter.

Now, lets move to another type of redirection, in which we need to redirect the custom action to any desired URL. There are several methods to accomplish this task. Here, I’m going to show two simple methods

1. This method is somehow similar to the method explained above. There is a minor change as follows:

namespace Excellence\Hello\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->setPath('excellence/index/add');
           return $resultRedirect;
      }
}

Here, we have just replaced the method setUrl() by setPath and have passed the URL to which we want to redirect.

2. You may find this method of redirection in several core files of magento too. Its quite simple and less complex than the previous one. Just use following code in your custom action:

return $this->resultRedirectFactory->create()->setPath('excellence/index/add/', ['_current' => true]);

If we use [‘_current’ => true]  then the objects being passed via query string will remain in the redirected URL but if we don’t use [‘_current’ => true] or use [‘_current’ => false], then objects will not be passed in the redirected URL.

URL Builder:

Suppose we want to redirect from a page to another page using anchor tag or similar, then we would need to set the href attribute to the URL to which it needs to redirect the current page. Here we should not use hard code like http://127.0.0.1/magento2/index.php/excellence/index/add/. Magento 2 comes with the concept of URL builder. it builds the actual URL of the controller action which is to be used. We have to just use:

$this->_urlBuilder->getUrl("excellence/index/add/")

If we print it then we will get the URL: http://127.0.0.1/magento2/index.php/excellence/index/add/. This method is somehow similar to classic method Mage::getUrl() of magento 1.

Magento2 – Registry

Magento registry stores data to memory which is specific to that request (rather than user or anything else), and persists for the duration of that request only. The principle is very simple really, the Mage class is instantiated as a singleton object for every request and the instantiated Mage object remains in memory, and is accessible in all classes (and templates) until the request completes and the response is sent.

As the object is a singleton, whenever you access it you get the same object. All that is happening is that you are storing values to this object, so when one class stores a value, and another accesses it they are both working on the same object and the second class is able to retrieve the value the first class set.

In magento 1, we were using Mage::register() and Mage::registry(). But in Magento2, the implementation is slightly different.  Here we use class Magento\Framework\Registry, and we can inject it in any constructor as follows:

namespace Excellence\Hello\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Registry $registry)
    {
    	$this->registry = $registry;
        return parent::__construct($context);
    }
     
    public function execute()
    {
        #some code here
        
        $this->registry->register('test_var', 'this is a test!');

        #some code here
    } 
}

To access the variable, we will use following code snippet:

$this->registry->registry('test_var');

Basically, you can set a variable in registry in controller, block and access it anywhere like helper, black, model etc but only within the same request.

Note: We will have to inject the class Magento\Framework\Registry again in constructor of the class in which we are going to access the registry.