Assigning default values in CFormModel rules

Hi all,

I’d like to assing default values to my CFormModel attributes, via the rules array. I tried this:


class MyForm extends CFormModel {

    public $dummy;


    public function rules() {

        return array(

            array('dummy', 'default', 'value' => 'Hello'),

        );

    }

}

But when rendering the form, the default value does not get populated. What am I doing wrong?

Note: I managed to set the default value for “dummy” from my controller without any problems, however I’d like to do that from the model. I’m using WAMP stack, Apache 2.2, PHP 5.3, Yii 1.1.7, FF4.

Thats because validators are run on validation ( when calling $model->validate() or $model->save() ).

this validator sets the default value when no value has been submitted/assigned.

you may instead try


class MyForm extends CFormModel {

    public $dummy = 'Hello';


    public function rules() {

        return array(

            array('dummy', 'default', 'value' => 'Hello'),

        );

    }

}

Your form will have ‘Hello’ as value for dummy when rendered. if the user deletes this value and submmits the form then our CDefaultValueValidator comes into play, and instead of saving an empty value to the databse (or whatever) it will set dummy to ‘Hello’ again.

[quote=“Asgaroth, post:2, topic:38507”]

Thats because validators are run on validation ( when calling $model->validate() or $model->save() ).

That pretty much explains it, I overlooked the fact that default is just another validator. Thanks, great answer!

So if I need to set something more sophisticated than “Hello” as a default value, I guess I should stick to assigning the value from the controller, or maybe overriding the CModelForm __construct()? (I don’t know if the latter would be an acceptable approach for this, I’m pretty new to Yii.)

the best place would be the CModel::init() method. its called after the constructor :)

Perfect! Calling init() works as a charm. Thanks a lot.