CGridView filter on virtual attribute

Dear All,

I am having a membership table with one of the field is "status". This field is to show that a membership is still "active" or "expired". Expiration is determined by the expired date field.

Any idea on how to implement this? At the moment, my workaround is by adding code in afterFind to check whether it is expired, if the membership is expired then, we set the status to “expired”. FYI, there are only 2 status “active " or 'expired”. The thing is that value as the result of added code on the afterFind and what is stored in DB are different. Hence, I have difficulty on the filtering it on a CGridView.

I come up with an idea to use virtual attribute ‘status’ and remove it from the membership table. Hence, I can make sure that the value is always the same. But, the problem is that, I don’t know how to implement the filtering on this field on the CGridView.

Any helps?

I think you need something like this, but this one is not related to a PHP expression :


At some point you’re using a CDbCriteria object to construct your database query. If you’ve created a virtual attribute for the model, you can add these lines to your criteria:

Say, inside your membership model:

    public function search()


        $criteria=new CDbCriteria;


        ... comparing standard attributes

        if ($this->status === "active")

            $criteria->addCondition('ExpiredDate is null');

        if ($this->status === "expired")

            $criteria->addCondition('ExpiredDate is not null');

Brilliant. I never think about this before. Thanks a lot for your help.