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 ?

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 :)

  • Tried in Magento 2.2.4, its working like a charm – amit_game Jun 19 '18 at 11:55
3

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]);
  • do you know how I would do this in Javascript? – peedee Dec 15 '16 at 3:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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