Routing in custom form field

Hello!

I’m creating a custom form field starting from here.

This custom field uses a couple of routes that I implemented in config.php file.
Everything works fine, but I would like to move these routes from config.php to the field class to make installation esier and the custom field more “compact”.

I tried with:

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

And with (watching how structured field works):

  public function routes() {
    return array(
    );
  }

But nothing seems to work.
Is it possible?
Any suggestion?

Thanks!

1 Like

To make the field routes work (like with the structure field), you need a field controller. An example is the one of the structure field at panel/app/fields/structure/controller.php. Have you put your actions in such a file?

Also, please note that the routes will then be relative to the field URL, which you can build like in the url() method of the structure field.

Maybe sometime add docs about field routes and field controllers? Lower the bar for plugin developers.

Thanks for the feedback. It is already on our list for new documentation and will definitely get into the docs at some point.

1 Like

Great!

Another thing while I’m at it. I think it’s difficult to find the lastest updated docs. It’s probably possible to using github but it would be nice to have some kind of feed / blog on latest updated / created docs. What do you think about that?

I added it to the list. I can’t promise anything, but we will look into it.

1 Like

@lukasbestle thanks for the tips!

I tinkered a bit and it’s works!
Controller is a good think, but it’s not necessary, you can you:

public function routes() {
  return array(
    array(
      'pattern' => 'something/(:any)/(:any)',
      'method'  => 'get',
      'action' => function($var1, $var2)
      {
          // do something
          return response::json(array($var1));
      }
    )
  );
}

The most important thing is to relate the route to the field URL:
http://www.sitename.COM/panel/pages/PAGE_NAME/field/FIELD_NAME_IN_BLUEPRINT/CUSTOM_FORM_FIELD_NAME/something/var1/var2

Thanks!

3 Likes