Search code examples
yii2

DefaultValidator in DynamicModel


In a Controller I use this formModel:

$formModel = new \yii\base\DynamicModel(['field']);
$formModel->addRule('field', 'integer',['min'=>1]);
$formModel->addRule('field', 'default',['value'=>20]);
Yii::debug("formModel:".print_r($formModel->attributes,true));

But the app.log says:

formModel=Array
(
    [field] => 
)

Why is field not initialized with 20? How to use the DefaultValidator in a DynamicModel?


Solution

  • The yii\validators\DefaultValueValidator is executed during the validation. Your code doesn't run validation so the default validation rule is never applied.

    You can add the validate() call to your code:

    $formModel = new \yii\base\DynamicModel(['field']);
    $formModel->addRule('field', 'integer',['min'=>1]);
    $formModel->addRule('field', 'default',['value'=>20]);
    $formModel->validate();
    Yii::debug("formModel:".print_r($formModel->attributes,true));
    

    If you want to initialize the field value without validation you can pass the init value in constructor instead:

    $formModel = new \yii\base\DynamicModel(['field' => 20]);
    $formModel->addRule('field', 'integer',['min'=>1]);
    Yii::debug("formModel:".print_r($formModel->attributes,true));