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'); ?>
lalithkumar
  • 3,480
  • 4
  • 24
  • 40
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
  • You're talking about this? http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#radioList()-detail If so, that seem to have $options where you can set the default selection. – methode Jul 11 '15 at 11:15
  • i already gone through this doc, if anyone find the attribute name, then i want a demo? – Insane Skull Jul 11 '15 at 11:21
  • 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. – ScaisEdge Jul 11 '15 at 11:51
  • 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 .. – ScaisEdge Jul 11 '15 at 12:15

4 Answers4

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.

Insane Skull
  • 9,220
  • 9
  • 44
  • 63
tarleb
  • 19,863
  • 4
  • 51
  • 80
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'); 
?>
Mahmut Aydın
  • 831
  • 13
  • 21
-1

You have to set 'config' attribute.

$model->config = 1;

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

tarleb is right.

Stefan
  • 35
  • 2
-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();
methode
  • 5,348
  • 2
  • 31
  • 42