Search scenario (CGridView, etc.): avoid default values from database as search condition.

Yii has a neat "trick" that will assign default values to new CActiveRecords. When performing a search() though, this is pretty annoying as they automatically apply as filter values.

The issue is not new, and I have stumbled on it again after more than one year went by since my "initial" encounter with the side effects of this feature.

So I now decided to update my Gii model generation and share the solution as a tip.

I STRONGLY suggest that you update ALL of your models with the following code to avoid bad surprises.

... extends CActiveRecord {
	 * Unset attributes of model when this is a search scenario
	 * to avoid unwanted side effects of initial values set
	 * in the database.
     * @see CActiveRecord::afterConstruct()
	protected function afterConstruct() {
	    if($this->getScenario()==='search') {

So the above code just unsets the attributes that were assigned automatically when the record is used as a filter for a search scenario.

You should also add this to your Gii basemodel.

So the above code simply