1

I'm writing a plugin. I'd like it so that a request to view the page is processed via a Controller rather than goes straight to a template (following an MVC pattern).

So a GET request to the URL of the plugin calls a Controller method, which makes an API call and then displays a template.

Is this possible in CraftCMS? Can plugins have their own routes file? (I'm used to Laravel)

This is what I've tried so far:

public function init(): void
{
    parent::init();

    // Register an event for handling custom routes
    Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_SITE_URL_RULES,
        function(RegisterUrlRulesEvent $event) {
            $event->rules[] = [
                'pattern' => 'my-amazing-plugin-yeah',
                'route' => 'my-amazing-plugin-yeah/my-controller/my-action',
                'verb' => ['GET'], // Specify GET as the allowed HTTP method
            ];
        }
    );
}

I would expect this to break once admin/my-amazing-plugin-yeah was called in the browser, but it's displaying index.php correctly.

1 Answer 1

1

You had the right idea with the RegisterUrlRulesEvent, you just need to specify in the array the url as the key and the path to your controller as the value.

Event::on(UrlManager::class, UrlManager::EVENT_REGISTER_CP_URL_RULES, function(RegisterUrlRulesEvent $event) {
            $event->rules += [
                'my-amazing-plugin-yeah-url' => 'my-amazing-plugin-yeah/my-controller/my-action',
            ];
        });

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.