Search code examples
formsyii2radiobuttonlist

Yii2 - create radioList not enclosed by label


How do you create an activeRadioList in yii2 where the checkboxes are not wrapped in labels? Ie. The label and input are adjacent to each other.

The following creates a list of radio buttons where each input is wrapped in labels:

<?= $form->field($model,'myattribute')->radioList(['n'=>'No','y'=>'Yes']) ?>

You can create one radio button that is not wrapped in a label by setting the second argument to false:

<?= $form->field($model,'myattribute')->radio(null,false) ?>

But how do you do this for a list? (FYI. I need this to work with the materializedcss framework in case your wondering).


Solution

  • you just need to set label property false

    <?= $form->field($model,'myattribute')->radioList(['n'=>'No','y'=>'Yes'])->label(false); ?>
    

    Updated answer

    So in that case you need to use custom logic as follows.

    <?=
            $form->field($model, 'myattribute')
            ->radioList(
                    ['n'=>'No','y'=>'Yes'], [
                'item' => function($index, $label, $name, $checked, $value) {
    
                    $return = '<input type="radio" name="' . $name . '" value="' . $value . '">';
                    $return .= '<i></i>';
                    $return .= '<span>' . ucwords($label) . '</span>';
                    return $return;
                }
                    ]
            )
            ->label(false);
    ?>