开发者

CakePHP view method using post title as url

开发者 https://www.devze.com 2023-03-12 03:26 出处:网络
I have the following link structure for my portfolio: <?php echo $this->Html->link($post[\'Portfolio\'][\'title\'], array(\'controller\' => \'portfolio\', \'action\' => \'view\', Infle

I have the following link structure for my portfolio:

<?php echo $this->Html->link($post['Portfolio']['title'], array('controller' => 'portfolio', 'action' => 'view', Inflector::slug($post['Portfolio']['title'])), array('title' => $post['Portfolio']['title'])); ?>

Which gives urls like: http://driz.co.uk/portfolio/view/Paperview_Magazine

However how do I get my controller to show the item based on the title?

So far I have this but have not been able to get it to work and just get a blank page (so I ALSO need to check the format is correct and that their is a relevant item)

function view ( $title )
{

    $posts = $this->Portfolio->find('first', array('conditions' => array('Portfolio.title' => $title)
    ));

    if (empty($title))
    {
        $thi开发者_JAVA百科s->cakeError('error404');
    }
    $this->set(compact('posts'));
}


@Ross suggested that you search using Portfolio.slug so here's how you could do this:

  1. Add a field to your database table called slug. You'll most likely want a VARCHAR with sufficient length to accommodate the slug.
  2. When you create or update a "Portfolio" record, use the Inflector::slug method to generate a slug and save it to your database. You could always do this in the model's beforeSave event or if you prefer, in the controller before saving the data.
  3. Update the find call to look for Portfolio.slug instead of Portfolio.title.

Unfortunately, there's no way to reverse the Inflector::Slug function as it removes certain characters like apostrophes, quotes, parentheses, etc. which is why you need to save the slug to your database if you want to search for it.

Here's how you could use the beforeSave event in your model:

public function beforeSave(array $options = array())
{
  // If the title is not empty, create/update the slug.
  if ( ! empty($this->data[$this->alias]['title'] )
    $this->data[$this->alias]['slug'] = Inflector::slug($this->data[$this->alias]['title']);

  // Returning true is important otherwise the save or saveAll call will fail.
  return true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消