Insane Skull
Insane Skull

Reputation: 9358

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

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'); ?>

Upvotes: 12

Views: 28776

Answers (4)

Mahmut Aydın
Mahmut Aydın

Reputation: 869

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'); 
?>

Upvotes: 2

tarleb
tarleb

Reputation: 22599

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.

Upvotes: 29

Stefan
Stefan

Reputation: 35

You have to set 'config' attribute.

$model->config = 1;

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

tarleb is right.

Upvotes: -1

methode
methode

Reputation: 5438

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();

Upvotes: -3

Related Questions