views:

37

answers:

1

Hi folks,

I have a website that I want to modify the routing on. My problem is that in this specific scenario I'm not sure that what I want is even possible.

I have a projects controller with an index action/view and a view action/view. When I go to projects/ i see a list of projects. when I go to projects/view/project-slug I see that specific project. what I'm hoping to do is change projects/view/project-slug to projects/project-slug. So pretty much from the same action (index) I want to have one view for when the project-slug is set in the URL and one for when it is NOT set.

How do I do this?

Thanks,

Jonesy

+2  A: 

In routes.php:

Router::connect(
    '/projects/:slug', 
    array('controller'=>'projects', 'action'=>'view'),
    array(
        'pass'=>array('slug'),
        'slug'=>'[0-9a-z-]+'
    )
);
// Reverse route format (e.g. in HtmlHelper::url calls):
// array('controller'=>'projects','action'=>'view','slug'=>$some_slug)

Router::connect(
    '/projects',
     array('controller'=>'projects','action'=>'index'),
     array('action'=>'index')
);
// Reverse route format: array('controller'=>'projects','action'=>'index')

I find it helpful to put the reverse-route in a comment after each Router::connect so I can remind myself how to rebuild a given route later on.

Daniel Wright
thanks alot Daniel! I've got a lot to learn about Cake's routing!
iamjonesy
Although now when I navigate to the add action of my projects controller it thinks it is a project slug. How do I fix this?
iamjonesy
You would define another route for `/projects/add`, and place it above the two routes I defined in my answer.
Daniel Wright
loving this routing discussion
the0ther