Default fields values in CActiveForm


I began building an application using the new Yii 1.1.1 and its scaffolding features ("crud" pages). Making the frame of an application is even faster than before!

But when I first load the "Manage" page, in the "Advanced search" some search fields are filled by default. These fields are those that have a non-null default value in MySQL. How should I erase these values?

I could not find anything about this, neither in the doc nor in the forums. A quick dive into web/widgets/CActiveForm.php led me to CHtml::active* where the attributes are read. After browsing a little, I came to the conclusion that I had to overload my model constructor because the CActiveRecord constructor always filled the default values even on a ‘search’ scenario.

class Keyword extends CActiveRecord


	public function __construct($scenario = 'insert')



		if ($scenario === 'search') {

			$this->category = '';

			$this->role = '';



Did I miss an easier solution? I think the default CActiveRecord should be modified, but I may be wrong. Anyway, shouldn’t this at least be documented?

Yes, AR will load the default value set in the database. At this moment, you can only overwrite these by setting them explicitly in init() method.

I believe there exists a default value validator for CActiveRecord that has an option to enforce its value even when the attribute is not blank. You can specify that in the rules() method of your model, attached to the correct scenario. Maybe that helps?

The default value validator will not help in this case. The default value is not applied until validation is performed. This is usually used when you want to apply a default value if the user leaves the form field blank, not to pre-populate it.

Yeah, I have always manually set the fields to NULL before rendering the form too.

I am also encountering this ‘feature’ which is quite annoying. I don’t understand why the default values should be populated in the ‘search’ scenario. Typically one does NOT wish to pre-filter searches by the defaults. In my case, I have several boolean (bit) fields with default of 0 or 1 (false or true). Filtering the records by all the defaults give me (2) out of (22) records when I first open the Admin/CRUD view!

I’d suggest that CActiveRecord.__construct() be changed to not load the attributes if the scenario is ‘search’. But I really don’t like hard-coding “search”. Is there an easier way?

Yii ticket has been logged for this request.

Since this was an pre-unsetAttributes() thread, I think it’s appropriate to paste Qiang’s answer here