CakePHP, Using Edit For Add/Edit Functions, & Plugins (Oh My!)

When I work on a project I usually combine my add/edit functions into just edit. This saves some space in my controllers and makes maintenance a lot easier as I have only one function to edit instead of 2.

To accomplish this in Cake, you’d just do something like this:
Router::connect('/:prefix/:controller/add', array('action' => 'edit', "admin" => true));
This will map your controllers in your “app/controllers” folder nicely.

But let’s say you’re building an app that includes plugins. You may think “Ha hah! I’ll just slap this in my routes.php file”:
Router::connect('/:prefix/:plugin/:controller/add', array('action' => 'edit', "admin" => true));
And it will work..kinda.

More specifically, it will work for the subcontrollers of your plugin. For example, if you have a news plugin, and the news plugin has a comments controller, the above route will work, because it will map “/admin/news/comments/add” to /admin/news/comments/edit”.

HOWEVER!! This will NOT work for the news controller itself
Dramatic Chipmunk

*ahem* Luckily, the fix is easy and only took me 2 days to figure out (hey, I have kids; things get put aside…yeah, that’s my reason)
Router::connect('/:prefix/:plugin/add', array('action' => 'edit', 'admin' => true));
Now you can access “/admin/news/add” as you’d expect!

Advertisements