8

I cannot find any documentation that specifies how to link to controller actions which return a rendered template in CP.

Let's say I have a plugin called waffles and my namespace is Very\Waffles. I have a controller named SyrupController and it's residing in Controllers directory (note the capitalized directory name). So the namespace for it would be Very\Waffles\Controllers.
An action actionPour() - how can I register a route that would call this action if I land on the /admin/waffles URL?
I've walked through the steps with a debugger and It's trying to check if a SyrupController exists but how can it, if only Very\Waffles\Controllers\SyrupController exists? Thus it fails to register that route and fails.

Any help much appreciated!
Here's some code:

    Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_CP_URL_RULES,
        function (RegisterUrlRulesEvent $event) {
            $event->rules['waffles'] = 'waffles/syrup/pour';
        }
    );

It shouldn't be possible to link to a controller by using this string, so I'm guessing an array that specifies the SyrupController::class, but there's no documentation about it.

Thanks!

2 Answers 2

9

Apparently I figured it out. Would still like a better way of doing this, but here's the solution I found to be working:

In your Plugin class, you have to add a public $controllerMap array. For my example plugin above, here's what I would have to add to that $controllerMap array:

use Very\Waffle\Controllers\SyrupController;

class Plugin extends \craft\base\Plugin
{

    /** @var array */
    public $controllerMap = [
        'syrup' => SyrupController::class,
    ];

    // other code here, obviously
}
0
7

Your code should work as you suggested without the additional stuff.

Event::on(
    UrlManager::class,
    UrlManager::EVENT_REGISTER_CP_URL_RULES,
    function (RegisterUrlRulesEvent $event) {
        $event->rules['waffles'] = 'waffles/syrup/pour';
    }
);

Clarification:

plugin-name = Waffles

controllerName = SyrupController

functionName = actionPour()

With the information above you should be able to call the function in the controller with waffles/syrup/pour, and as you stated, the rules['waffles'] would be your URL.

2
  • 2
    At the time of the question Craft plugins had no automatic controller map included. Now they have it but earlier you had to do what Gustav described Commented Sep 22, 2018 at 18:04
  • I had wondered if that was the case. Thanks for clarifying. Commented Sep 23, 2018 at 13:08

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.