I have a model of a visitor. In this model and in the database there is a field date of birth. Sometimes I need the age of the visitor, but I dont want to store this value in the database because I would continously need to update it. So I added a variable to my model class called age. Using the afterFind method of the model class I fill the age variable with the correct age based on the date of birth. This works fine in all views (DetailView, Gridview). The only problem is, I would like to sort the GridView based on age. When enabling sorting, all column headers are sortable except the age column. When adding age to the rules -> safe on search array, I get an SQL error, column not found. Clearly Yii searches the database table for the column, which its not going to find.
Is there a way I can achieve sorting on age? Perhaps I need to define the age variable in another way?
You could try using the DOB field, name it age and calculate the age in the value part of the columns array. Sorting would work because DOB is the same as age only the other around.
You don’t need to fill a variable in afterfind, you can create a method in the model:
public function getAge()
{
return (strtotime('now')-strtotime($this->date_of_birth))/(60*60*24*365);
}
Or something like that.
What about sorting? You cannot sort for age, because you have not this in database. If all the people in your database are alive, you can upside down sort for date of birth, and the trick is done.
For do that, edit the Sort of CActiveDataPovider (in model::search()):
The only thing that doesn’t work is when I search for a specific value by entering it in the textfield in the header column. If I understand you correctly I will not get this to work because this field searches directly in the DB.