How to add default value in Yii2 using Dynamic Form

1.1k views Asked by At

is there a way to add a default value in Yii2 to a dynamicform field?

something like AfterInsert Add some value to the new added field

<?= $form->field($newmodelDetConta, "[{$i}]abono")->label(false)->textInput
                            ([
                                'maxlength' => true,
                                'value' => '0.00',
                                'class' => 'form-control txtabono',
                                'style' => 'text-align: right',
                                'type' => 'number',
                                'type' => ['number',2],
                                'format'=> ['decimal',2]
                            ]) ?>

this only works for the first field, but when I click add the value is empty and not "0.00"

1

There are 1 answers

0
Ripper On

If you expect default value on dynamic column, you can set column default value directly in database, example ... on that link is example how to do it, if you do not use phpmyadmin or any other database GUI

or set value to model in action in your controller, so it will be already filled when you will fill out form like this:

$model = new SomeModel();
$model->some_attribute = 'some default value';

or you can use default "validator" in rules in your model, but this is mostly used for models that do not extend from ActiveRecord

public function rules()
{
    return [
        // ...
        [['some_column'], 'default', 'value' => 'some value'],
        // ...
    ];
}

or if you have set up virtual attribute you can set its value directly in model

class SomeModel extends Model
{
    public $some_attribute = 'some value';
    // ...