Shaeldon
Shaeldon

Reputation: 883

Yii2 preselect radiobutton value

I know I can use

 <?= $form  ->field($model, 'subject')
            ->textInput(array('value' => 'VALUE'))
            ->label('Titel'); ?>

to prefill a Textfield, but how can I do it for a radioList?

<?= $form  ->field($model, 'locations')
           ->radioList($regionen)
           ->label('Regionen');

I could use ->textInput again but this transforms the whole List into a single Textfield

Alternativly: Is there a better way to modify a database record? Currently I'm trying to set all values into a new form.

Upvotes: 1

Views: 7449

Answers (2)

Vasilis Lourdas
Vasilis Lourdas

Reputation: 1179

Put the value that you want selected in the locations attribute of your $model and after rendering, it will be pre-selected in the radio list. That is:

$model->locations = ....

I assume that locations is a foreign key to some other table (or maybe a fixed list of strings).

Upvotes: 3

Aniruddha
Aniruddha

Reputation: 806

Referring the documentation :

Pass the second parameter, options[] to radioList()

$options = [
    'item' => function($index, $label, $name, $checked, $value) {

        // check if the radio button is already selected
        $checked = ($checked) ? 'checked' : '';

        $return = '<label class="radio-inline">';
        $return .= '<input type="radio" name="' . $name . '" value="' . $value . '" ' . $checked . '>';
        $return .= $label;
        $return .= '</label>';

        return $return;
    }
]

<?= $form->field($model, 'locations')
         ->radioList($regionen, $options)
         ->label('Regionen');

Hope this helps..

Upvotes: 2

Related Questions