convert post title to valid url

hi there,

i was wondering if there is a function inside the framework that can convert post title to valid url’s.

so instead of using /post/read/1.html you can use /post/read/this-is-my-first-post.html.

thank you

You can edit the loadModel function, in order to search by title and not by pk.

The question is not technical but logical. What happens if 2 posts have the same title?

Take a look at this thread.

thank you!

if i want to make a function like CHtml::link, but than for this kind of urls is this than the correct way:




<?php $this->widget('application.extensions.MySlug', array('string' => 'Dit is mijn eerste post.', 'space' => '@')); ?>






<?php


class MySlug extends CWidget

{

	public $string;

	public $space;


	public function init() {

		if (!isset($this->space)) $this->space = '-';

		if (function_exists('iconv')) {

			$this->string = @iconv('UTF-8', 'ASCII//TRANSLIT', $this->string);

		}


		$this->string = preg_replace("/[^a-zA-Z0-9 -]/", "", $this->string);

		$this->string = strtolower($this->string);

		$this->string = str_replace(" ", $this->space, $this->string);


		echo $this->string;

	}

}



Better to put the logic into the model. Let’s assume you have a Post model with a title column. You could do this:





// urlManager config


'rules' => array(

   'post/read/<id:[0-9]+>-<slug:.+>' => 'post/read',

),








// within Post.php


public function getUrl()

{

   return Yii::app()->createUrl('post/read', array('id' => $this->id, 'slug' => $this->createSlug($this->title)));

}


public function createSlug($title)

{


   // convert the raw title into an url friendly format here


   return $slug;


}




After that you can access the final url directly:




$post = Post::model()->findByPk(1);

echo $post->url; // Returns for example: /post/read/1-this-is-url-friendly.html



Make sure to read everything in the other thread. You may don’t want to have any post id’s in the url for example…