CTimeStampBehaviour for setting create_time and update_time resetting create_time with afterFind()

StackOverflow https://stackoverflow.com/questions/13416917

Question

I am using CTimeStampBehaviour for setting create_time and update_time resetting create_time with afterFind() in model, Basically I am setting the format of date to be displayed on the front end. But this does not work as create_time is sent 0000-00-00 00:00:00 on using model's afterFind(). It works fine when I comment afterFind() in model.

I have used this function in my model:

public function behaviors(){
return array(
    'CTimestampBehavior' => array(
        'class' => 'zii.behaviors.CTimestampBehavior',
        'createAttribute' => 'create_time',
        'updateAttribute' => 'update_time',
        'setUpdateOnCreate'=> true,
    )
);
}

I have seen the documentation on CTimeStampBehavior class on yii site, it has a reference to afterFind() inheritence but does not suggest how to use it. I am using afterFind() in model like this:

protected function afterFind() {
parent::afterFind();
$this->create_time = Yii::app()->dateFormatter->formatDateTime(
        CDateTimeParser::parse(
            $this->create_time, 'yyyy-MM-dd hh:mm:ss'
        ), 'short', 'short'
    );
return true;
}

Can anyone suggest why the create_time is being zero filled when using afterFind()?

Était-ce utile?

La solution

create_time will be zero filled when you save the model after loading it and afterFind() changed the value of create_time to a formatted date. This is because when you save your model now your are trying to send the formatted value to the database which does not understand the format and set the value to 0000-00-00 00:00:00.

When you implement an afterFind() method to change values format, you have to implement a beforeSave() method to set the value back to a format that can be understood by the database.

It is generally a bad idea to format values directly on the model. When you are doing strict MVC it is the job of the View to format your Date correctly.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top