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!

Leave a comment

1 Comment

  1. Dunhamzzz

     /  July 16, 2010


    Thanks for covering the exact thing I was looking for!

    I had to make one slight alteration to your routes to allow them to accept variables on the end of the /add urls eg: /admin/links/add/productId:84 (to pre-fill the product)

    All I had to do is add a /* onto the end of the routes:
    Router::connect(‘/:prefix/:controller/add/*’, array(‘action’ => ‘edit’, “admin” => true));

    Thanks again.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: