I have been trying to do the following method to create urls like:
domain.com/portfolio/This_is_a_test_post
function view ( $title )
{
you can't do that. When saving the post, you should slug the title already; or if you want to keep the title, put the slug to another field to find later.
function view ( $title = null ){ if(!$title)$this->redirect(array('action'=>'index')); $post = $this->Portfolio->find('first', array('conditions' => array('Portfolio.title' => $title))); $this->set(compact('post')); }
you can use this lib support to convert urls without more efforts
http://someguyjeremy.com/blog/slugs-ugly-bugs-pretty-urls
It does not work because you are applying the Inflector::slug function to the name of the column.. Try the other way around.., add a slug column to your post, and create the slug when you add the post using the Inflector, try something like this when you add your post:
$this->data['Post']['slug'] = Inflector::slug($this->data['Post']['title']);
and on your controller, do this:
function view($slug = null) {
if (is_null($slug)) {
$this->cakeError('error404');
} else {
$post = $this->Post->findBySlug($slug);
$this->set(compact('post'));
}
}
that should do the trick.. i hope it helps..
I would recommend using the ID for addressing content on your website, this way you do not have to worry about dealing with title/slug changes. For a SEO perspective you can easily use the Slug without doing anything with it technically:
function view($id) {
$this->Post->id = $id;
$this->set('post',$this->Post->read());
}
And in your view, create links like this:
$this->Html->link('name of the link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id'], Inflector::slug($post['Post']['title'])));
Now your URL's will look like this:
domain.com/posts/13/This_is_a_test_post
Note that the slug isn't doing anything, but is giving you the benefit of SEO