Let say I don’t want to save an attribute (like the created date) in a model, how can I do that the Yii way ?
unset($this->attribute) //?
Now, let say I want to save the created attribute, but I need to format it before displaying it. In the afterFind method I use the dateFormatter to display the timestamp in a view. If this view is a form, and I validate it, the script in the controller goes this way :
Retrieve the model with findByPK (here, the afterFind method is called and the created attribute is overrided with the friendly format)
Massive assignement (the created attribute is not assign cause not in the validated form)
Validation (let say it goes fine)
before save, change back the created attribute to a timestamp
save
As you can see, when I retrieve the model, the created attribute is automatically changed to a friendly format. So I have to change it back to a timestamp format before save.
It works, but he feels wrong to me
Can I override the magic __get() function to retrieve the created attribute as a friendly format ? Since the created attribute is never changed in the model, I don’t have to mess with afterFind and beforeSave.
Right now, I use the virtual attributes. I tried the afterSave/beforeSave methods, but it feels a lot of code for almost nothing.
I have to say, it is not just for the created attribute, but also for the image attribute.
My model return the image name (like 12345.jpg). And I want the model to return the whole path (like /assets/img/12345.jpg) or if there is no image, a default one (like /assets/img/default.jpg).
I don’t want to store the path in the database (since it can change), and I need to set a default image. To finish, I can’t imagine a test in every view like this one :
Not dry ! It seems normal to me that the model return the whole path so I don’t have to write it in every view. After all this is datas coming from database, and the path is a part of this data (even if not in the database).
For now, i will stick to the virtual attributes, but if you have any better idea