How to pre-select / check the default switch in yii2 RadioList ()?

I want the radio button selected in my form.

<?= $form->field($model, 'config')->radioList(['1'=>'Automatic Entry',2=>'Manual Entry']) ->label('Barcode/Book No Generation'); ?> 
+7
html php yii2 active-form
source share
4 answers

Preselected values ​​are taken from $model->config . This means that you must set this attribute to the value that you want to preselect:

 $model->config = '1'; $form->field($model, 'config')->radioList([ '1' => 'Automatic Entry', '2' => 'Manual Entry', ]); 

The corresponding document for this is in the ActiveForm class.

+20
source share

if you want to use the standard radio value, you can use the following codes:

 <?php $model->isNewRecord==1 ? $model->config=1:$model->config;?> <?= $form->field($model, 'config')->radioList( [ '1'=>'Automatic Entry', '2'=>'Manual Entry' ])->label('Barcode/Book No Generation'); ?> 
0
source share

You must set the attribute 'config'.

 $model->config = 1; 

You will have the first radio button selected when loading the form.

Tarleb is right.

-one
source share

A long shot in the dark, since I'm not very familiar with yii2, but based on the documentation you can do something like this.

 $form->field($model, 'config')->radioList([ '1'=>'Automatic Entry', '2'=>'Manual Entry', ], [ 'item' => function ($index, $label, $name, $checked, $value) { return Html::radio($name, $checked, ['value' => $value]); }, ]); // [...] ActiveForm::end(); 
-3
source share

All Articles