I have a custom module that is adding sections to the CP, like this:
// Register CP routes
Event::on(
UrlManager::class,
UrlManager::EVENT_REGISTER_CP_URL_RULES,
function(craft\events\RegisterUrlRulesEvent $event) {
$event->rules['<controller:(subscriptions|purchases)>/<action:>'] = [
'route' => 'module/<controller>/<action>',
'defaults' => [
'action' => 'index',
],
];
}
);
// Add CP nav items
Event::on(
Cp::class,
Cp::EVENT_REGISTER_CP_NAV_ITEMS,
function(craft\events\RegisterCpNavItemsEvent $event) {
$event->navItems[] = [
'url' => 'subscriptions',
'label' => 'Subscriptions',
];
$event->navItems[] = [
'url' => 'purchases',
'label' => 'Purchases',
];
}
);
I have a SubscriptionsController
and a PurchasesController
, inside of which there is an actionIndex()
method that computes some stuff and renders the appropriate template like this:
return $this->renderTemplate('module/cp/subscriptions/index', [
'stuff' => $stuff,
]);
All this works fine, but I realized that the above registers some URLs that I do not want:
1) Controllers automatically register URLs in the format admin/actions/<module>/<controller>/<action>
AND actions/<module>/<controller/<action>
. I'm fine with the first one even though it causes duplicate URLs due to my custom <controller:(subscriptions|purchases)>/<action:>
rule, but the second one is problematic because they're not even CP URLs, yet they invoke a controller that is only meant to be used in the CP. It's causing an error when trying to render the template, because the module
template root is only registered for the CP with the code below:
// Set the base CP template directory
Event::on(
View::class,
View::EVENT_REGISTER_CP_TEMPLATE_ROOTS,
function (craft\events\RegisterTemplateRootsEvent $event) {
$event->roots['module'] = $this->getBasePath() . DIRECTORY_SEPARATOR . 'templates';
}
);
2) Craft automatically creates routes based on my template structure, meaning I can render the module/subscriptions/index.twig
template directly from this URL: admin/module/subscriptions
. This is also causing an error because the template requires variables that are passed to it in the controller action, but they're not set when rendering the template directly. I usually work around this issue on the front-end by setting the general.php
config setting privateTemplateTrigger
to an empty string ''
, but it doesn't seem to have any effect on the CP.
Any help with these two issues would be greatly appreciated. :)