How to preselect/check a default radio button in yii2 RadioList()?
Asked Answered
U

4

12

I want the radio button preselected in my form.

 <?= $form->field($model, 'config')->radioList(['1'=>'Automatic Entry',2=>'Manual Entry'])
     ->label('Barcode/Book No Generation'); ?>
Unreligious answered 11/7, 2015 at 9:55 Comment(4)
You're talking about this? yiiframework.com/doc-2.0/… If so, that seem to have $options where you can set the default selection.Argali
i already gone through this doc, if anyone find the attribute name, then i want a demo?Unreligious
In my test the radio button is normally preselected (ther first one) just a minor the 2 is better if you code '2' like the first.Pairoar
The default radio button (pre selected) is normally the first radio button. In my test ithe firts is always already cheked. And second point in your code the value 2 is not with quotes. I hope thi is more clear ..Pairoar
R
29

The preselected values are taken from $model->config. That means that you should set that attribute to the value that you want preselected :

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

The relevant doc for this is in the ActiveForm class.

Redoubt answered 11/7, 2015 at 20:36 Comment(0)
S
2

if you want to use default value of radio, you can use 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'); 
?>
Scriabin answered 7/5, 2017 at 22:6 Comment(0)
S
-1

You have to set 'config' attribute.

$model->config = 1;

You'll have first radio button selected when form is loaded.

tarleb is right.

Sanguinary answered 21/10, 2015 at 15:2 Comment(0)
A
-3

Long shot in the dark since I'm not awfully familiar with yii2, but based on the documentation you should be able to 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();
Argali answered 11/7, 2015 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.