* Create Slug field in your database table
If you prefer not to create slug every time someone goes to the homepage or the main news page, you can create slug field in your database table. It is a lot easier to keep track and you can modify the slug later as well.
* Use SlugBehaviors - http://www.yiiframework.com/extension/slug-behavior/
Installation was almost too easy. You download and extract the release file under models/behaviors
And in the model, add the following: (e.g. /protected/model/post.php)
public function behaviors(){
return array(
'SlugBehavior' => array(
'class' => 'application.models.behaviors.SlugBehavior',
'slug_col' => 'slug',
'title_col' => 'title',
'max_slug_chars' => 125,
'overwrite' => false
)
);
}
That's it!
* Modify config/main.php
The tricky part was how to modify the UrlManager in /protected/config/main.php as below:
'urlManager' => array(
….
'post/<id:\d+>/<slug>/*' => 'post/view',
'post/<id:\d+>/*' => 'post/view',
),
Make sure the order is correct or else they wouldn't work because the first rule is applied first.
* Use Chtml::link to create links
Then, you can use Chtml::link in the following way
echo CHtml::link(CHtml::decode($data->title), array('/post/view/', 'id'=>$data->id, 'slug'=>$data->slug));
Here are some articles that was helpful!
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#creating-urls under 3. Using Named Parameters