1

In Magento 1, we were able to do the following directly in a controller action method :

$this->_redirect('*/*/index');

Or in a more generic way:

$this->_redirect('adminhtml/controller/action');

What's the equivalent in Magento 2 ?

1
  • Hi Raphael, please create one chat and come to that please Commented Mar 26, 2016 at 7:40

2 Answers 2

5

To do the following in Magento 2, you must do the following in your execute method:

public function execute()
{
    /* Do your controller action stuff here */
    $resultRedirect = $this->resultRedirectFactory->create();
    $resultRedirect->setPath('adminRouteFrontName/controllerFolder/actionClass');
    return $resultRedirect;
}

You don't need to add the \Magento\Framework\Controller\Result\RedirectFactory to your constructor as it is already declared in the abstract class Magento\Framework\App\Action\AbstractAction so you have already access to the $this->resultRedirectFactory variable.

The parameters in my example are:

  • adminRouteFrontName: declared in your adminhtml/routes.xml
  • controllerFolder: name of the controller folder under Controller/Adminhtml
  • actionClass: name of your action class under the controller folder for example with Index.php it would be index, for Grid.php it would be grid and so on.

You can also still use the * as we used to do in M1.

You can also use parameters for example like this:

$resultRedirect->setPath('catalog/*/', ['store' => $storeId, '_current' => true, 'id' => $id]);
1
  • do you know how I would do this in Javascript?
    – peedee
    Commented Dec 15, 2016 at 3:24
4

I just want to add that Your Question and Your answer both are working for me :). I was searching for a simple method for redirection and accidentally I found that old method (of Mage 1) is still supported on Mage 2, I used the following code to redirect from my custom controller to product grid and it worked :)

$this->_redirect('catalog/product/index'); return;

I am not sure if it will be supported later or not but it was worth mentioning :)

1
  • Tried in Magento 2.2.4, its working like a charm Commented Jun 19, 2018 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.