Add date to url

I’m trying to add the date of a post to the url, but am having some trouble figuring it out, the below returns 1969/12/31 because create_time is null

Any idea on how to do this?

The other options is to add the date to the slug, but I wasn’t totally sure on how to do that, I’m using behaviorsluggable which only lets you choose column names from the table.


	public function getUrl()

	{

		return Yii::app()->createUrl('post/view', array(

			/*'id'=>$this->id,*/

			'year'=>$this->create_time ? date("Y/d/n", strtotime($this->create_time)) : 0,

			'slug'=>$this->slug,

		));

	}

How come you have a null ‘create_time’? Have you checked your table? Maybe you have a ‘0000-00-00’ value as null dates.

To avoid that, you should set ‘setEmpty’ in your model’s rules?


public function rules() {

    return array(

        …

        array('create_time', 'default', 'setOnEmpty' => true, 'value' => null),

Otherwise, you could use in your value the following condition instead: [font="Courier New"]!is_null($this->create_time)[/font]

No its not null, there’s values for every record, but what I’m guessing is that where I’m formatting it, the data hasn’t actually been retrieved yet so its null resulting in 1969/12/31

Ok I found the issue, the field type in the table was wrong and I was saving it with time() instead of formatting it properly, so when I was actually formatting it in the get url function it came out all messed up.

Thanks for your input