Is it possible to define panel routes inside a plugin file?

Hey Kirby Folks,

is there a clean way to add a custom panel routes inside a plugin file? I am developing an extended structure field that requires a modified (ajax)route for my modal forms.

The problem with just declaring the route inside the plugin file like this:

$router = new Router(array( 
  array(
    'pattern' => 'views/editor/extendedstructure/(:all)/(:any)/(:any)/(:any)',
    'action'  => function($id, $fieldName, $structuretype, $context){
        //do something
    },
    'filter'  => 'auth',
    'method'  => 'POST|GET',
    'modal'   => true,
  ),
));

is that the panel router throws an error and renders the “page not found” beforehand due to this previously matching route in panel/app/routes/view.php:

array(
   'pattern' => '(:all)',
   'action'  => 'views/ErrorsController::page',
),

I would like to avoid modifying the core routes. Thanks for ideas and suggestions.

Best,
Tim

1 Like

The problem isn’t that there’s another route that matches the URI. The problem is that you never tell your router to do its thing. :smiley:

You need the following code to process the router’s routes and call an appropriate one:

// Get the appropriate route from the Router
$route = $router->run(kirby()->path());

// Return if we didn't define a matching route to allow Kirby's router to process the request
if(is_null($route)) return;

// Call the route
$response = call($route->action(), $route->arguments());

// $response is the return value of the route's action, but we won't need that
// Exit execution to stop Kirby from displaying the error page
exit;
1 Like

Thanks for your reply. I already implemented the action handling. However, I assumed that kirby’s route was processed before my custom route. Wich was wrong. Your

exit;

made it :smile:

Thanks!

Why does not this work inside a plugin?

c::set('routes', array( $some_args ));

Would it not be easier to set it up this way if it would work?

I tried to put

c::set('routes', array(
  array(
    'pattern' => 'my/awesome/url',
    'action'  => function() {
       echo 'in custom route';
    }
  )
));

inside a plugin file but it dows not work. This way to define routes seems to be reserved to the config. Or am I getting things wrong?

Because the configuration options don’t get interpreted after the configuration has been loaded (they are being copied after loading the config).

No, because you would then overwrite all the other routes other plugins may have defined. Defining your own router is much more flexible in my opinion.

I use the following to define routes inside plugins:

kirby()->routes(array(  
    array(
        'pattern' => 'pattern', 
        'action'  => function() {
            
        }
    )
));
4 Likes