23

I am taking the Magento 2 fundamentals development course and the Admin Router / Controller exercise seems out of date. The router does work, but the controller does not, it always just re-routes to the admin homepage. Code for router app/code/Training/Test/etc/adminhtml/routes.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/framework/App/etc/routes.xsd">
<router id="admin">
    <route id="test" frontName="test">
        <module name="Training_Test" before="Magento_Backend" />
    </route>
</router>
</config>

Code for Admin controller app/code/Training/Test/Controller/Adminhtml/Action/Index.php:

<?php

namespace Training\Test\Controller\Adminhtml\Action;
class Index extends \Magento\Backend\App\Action
{

public function execute()
    {
    die("test reached controller");
    }
protected function _isAllowed() {
    return true;
    }
}

When I go to the admin url of admin/test/action/index it just redirects and nothing happens. If I add a constructor and use xdebug, it shows that it reaches the controller constructor, but it never does the execute part. What am I missing?

2
  • I hope in your code function _isAllowed return true. In example "return" instruction is absence
    – KAndy
    Dec 1, 2015 at 15:29
  • @KAndy yes it is, thanks though. Edited my question to show that. Dec 1, 2015 at 16:07

7 Answers 7

25

This happens because 'secret key' is missing when you just type in URL manually. Secret key feature is enabled by default and can be disabled here: Stores => Configuration => Advanced => Admin => Security => Add Secret Key to URLs. Then you should be able to reach your action.

7
  • @Alex Paliarush , how to make this work when security keys are enabled.?
    – Aswanth
    Apr 4, 2016 at 8:44
  • 1
    @Aswanth Just add your action to the menu, and click on it. In this case Magento will add proper security key to the request Apr 4, 2016 at 12:54
  • @AlexPaliarush Thanks It works for me.. and saved my time
    – ZOE RULE
    Feb 15, 2017 at 5:56
  • This was the problem but why don't the course say about this condition in the exercise? I lost some hours checking this... Grrrrrrr Feb 27, 2017 at 6:52
  • 2
    This is a temporary workaround that disables an intentional security feature - do not use this answer as a permanent solution on a public website! The answer fails to highlight that this is almost always a problem in your custom module routing logic - look there before resorting to this Jan 6, 2021 at 15:40
18

In routes.xml configuration file (companyName/customModule/etc/adminhtml/routes.xml). For me the solution was to have the route id and frontName have the same value. In your case this would be:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="admin">
        <route id="asw_advanved" frontName="asw_advanved">
            <module name="Asw_Sample" before="Magento_Backend"/>
        </route>
    </router>
</config>
3
  • Changed <route id="Bmanager" frontName="bmanager"> to <route id="bmanager" frontName="bmanager"> and now I can make a basic controller work as described the question body. Still no luck with my custom controllers. Edit: Actually one of my custom controllers started giving some errors. Much better than redirect with no erorrs. Jan 15, 2017 at 10:15
  • 2
    You legend this saved me much time! Jun 10, 2020 at 22:55
  • Thanks, it worked for me. What it happen? Sep 11, 2022 at 13:48
6

Maybe it's better to use that property:

/**
 * Array of actions which can be processed without secret key validation
 *
 * @var array
 */
protected $_publicActions = ['action_name'];
3

When attempting to access modules/functionality in the backend (Adminhtml), Magento checks for the presence of the secret Form Keys, and if/when someone does attempt to access an action and doesn't supply a FormKey (e.g: hotlinking the url) and/or supplies an Invalid FormKey - the Adminhtml AbstractAction (Magento\Backend\App\AbstractAction) will route the user Admin UIX's defined Startup page (which is usually the Dashboard page)

[This mechanism serves a "security checkpoint" to prevent users from accessing portions of the Backend that they don't have access to]


When accessing options from the Admin UIX Menu - Magento will automatically add the FormKey for you.


To prevent the check for FormKey you have two options:

(a) Turn off FormKey Validation

Navigation: Stores -> Settings : Configuration -> Advanced : Admin -> Security -> Setup "Add Secret Key to URLs" to "No"

It's very important to remember that doing so will turn off Secret Key Validation, and therefore may make your application vulnerable.

How To Turn Off FormKey Validation

(b) Turn off FormKey Validation for your controller

Specify the action(s) you wish to exempt, from the FormKey check, in the "$_publicActions" attribute of your Admin Controller.

protected $_publicActions = ['ENTER_NAME_OF_ACTION'];

Code Example:

class Index extends \Magento\Backend\App\Action
{
    protected $_publicActions = ['index'];

    public function execute()
    {
        echo "My Hello World! Controller";
    }

}
1
  • 1
    protected $_publicActions = ['ENTER_NAME_OF_ACTION']; save my day, thanks.
    – fudu
    Nov 20, 2020 at 7:39
3

The problem of the routing redirection with the security key enabled is the action url set in the menu.xml under /etc/adminhtml/

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
        <add id="Mycompany_Mymodule::top_level" module="Mycompany_Mymodule" resource="Magento_Backend::content" sortOrder="9999" title="My Module" parent="Magento_Sales::sales"/>
        <add action="mycompany_mymodule/profile/index" id="Mycompany::mycompany_mymodule_profile" module="mycompany_Mymodule" parent="Mycompany_Mymodule::top_level" resource="Magento_Backend::content" sortOrder="9999" title="My Module"/>
    </menu>
</config>

The important value is the action parameter in the menu item. Pay attention to set the name of the module declared into the routes.xml into the id parameter. In my case: "mycompany_mymodule"

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route frontName="mymodule" id="mycompany_mymodule">
            <module before="Magento_Backend" name="Mycompany_Mymodule"/>
        </route>
    </router>
</config>

I would like update this to help others!

If you use the getUrl() in the phtml file remember that the path that you will use is the name of the action defined in the menu.xml and not the frontName defined in the /adminhtml/routes.xml!

For instance this link will generates a Request validation failed for action :

<?= $block->escapeUrl($block->getUrl('mymodule/profile/edit', ['subscriptions_profile_id' => $profile->getId()])) ?>

this is the solution:

<?= $block->escapeUrl($block->getUrl('mycompany_mymodule/profile/edit', ['subscriptions_profile_id' => $profile->getId()])) ?>

Pay attention to the name of the module as parameter in the getUrl() method!

1

<input name="form_key" type="hidden" value="<?php echo $block->escapeHtml($block->getFormKey()) ?>" /> will help

but you could add a brickpoing to vendor/magento/module-backend/App/AbstractAction.php

if (!$_isValidFormKey || !$_isValidSecretKey) {}
0

My issue was max_input_vars in the php.ini file

Reference is at: https://magefan.com/magento2-blog-extension/redirect-issue-after-saving-blog-post

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.