Using Yii framework, what would be a right way to process an attribute before displaying it using CHtml::activeTextField()
Question
Say I have this line of code in the view.
<?php echo CHtml::activeTextField($model,'start_time'); ?>
start_time is a UNIX timestamp. When just displaying it in a view I can apply functions like date() on it. Where should I apply the formatting when I'm displaying it in a form, by using the above line of code? (This case of timestamps/dates might be special, but I'm also interested in how would one go about if it wasn't a date and I just want to work with
"value in database" <> "different representations of the value in different views.
Thanks =)
Solution
We generally extend CActiveRecord::afterFind()
to convert the data into a human-readable format and CActiveRecord::beforeValidate()
to transform it back.
If you need more than one format available at all times, you may want to give Yii's getters and setters a try.
Having both
CActiveRecord::getFieldName()
andCActiveRecord::setFieldName($value)
allows you to put CHtml::activeTextField($model, 'fieldName')
in your views. Obviously, you manipulate the underlying database column in those methods (apparently it's called start_time in your case). Hope this helps.
OTHER TIPS
I've used the CHtml::textField instead of CHtml::activeTextField like this:
<?php echo CHtml::textField(get_class($model).'[start_time]', date('Y-m-d H:i', $model->start_time)); ?>
I'll see if that works out in the long run.
In the same way instead of applying date method right there, I could have smth like $model->getSomeProcessedData(); Cool.. :]
IMO, afterFind() make you slow down your search and I don't think beforeValidate() play any role in display data. I prefer adding getttart_time() into the model class to override the getter of start_time value. There your formatting code only run when you need to display data.