简体   繁体   中英

cakePHP route element directs to missing controller action?

I'm trying to setup the following routing in cakePHP 2.3:

domain/news/slug

I've followed the cookbook guidelines on routing and the route that gets created is correct. The problem I run into is that when selecting the link I get the 'Missing Method in NewsController' error message.

Here's what I've configured:

    Router::connect(
    '/news/:slug/', 
    array('controller' => 'news', 'action' => 'view'), 
    array(
        'pass' => array('slug'),
        'slug' => '[^_]+'
        )
    );

I'm passing in the slug with a regular expression (any string that does not include an underscore).

This is my link in the index page:

        <?php echo $this->Html->link(
          $news['News']['title'], 
          array(
            'controller' => 'news',
            'action' => 'view',
            'slug' => $news['News']['slug']
            )
          ); ?>

As mentioned, the URL is built correctly, and looks like this: /news/test-slug-news-story

But when I click on it I get the 'Missing Method in NewsController' error message

Is it obvious what I'm missing, cause I've looked at this too long to be able to see it.

Thanks, Paul

You can try this one:

<?php
// Routing code
Router::connect('/news/:slug/', 
    array(
        'controller' => 'news', 
        'action' => 'view'
    ), 
    array(
       'slug' => '[a-zA-Z0-9_-]+'
    )
);
?>

<?php 
// HTML Link code.    
echo $this->Html->link(
    $news['News']['title'], 
    array(
        'controller' => 'news',
        'action' => 'view',
        'slug' => $news['News']['slug']
    )
); 
?>

If it is not working for you please let me know :)

Thanks

As mentioned above, I discovered that by having a backslash after 'slug' in the route setting, the controller interprets the ':slug/' as the controller action.

One of those 'doh' moments.

Code should look like this:

    Router::connect(
    '/news/:slug', 
    array('controller' => 'news', 'action' => 'view'), 
    array(
        'pass' => array('slug'),
        'slug' => '[a-zA-Z0-9_-]+'
        )
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM