Suppose I have a model variable $model->start_date
In my update form, this is displayed in the input field as: 2012-10-10 15:00:00
However I want to display it as: 10 October 2012
So in my controller update action I do:
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$model->start_date = date("d F Y", strtotime($model->start_date));
...
}
This works fine for me. I also do the same for the ‘View’ action and anywhere else I need to display $model->start_date. I created a function in the model called getStartDate() which does this (I just do $model->start_date = $model->getStartDate() in my controller actions so that I don’t have to keee repeating the code).
However I was wondering whether it is possible for $model->start_date to have this "transformed" value by default whenever it is read from the DB. This would save me from having to call the function in every place it needs to be displayed.
You can use the beforeSave() method to automatically save the value in the correct database format, and the afterFind() method to automatically make it available in your desired displayable format.