Brett
Brett

Reputation: 20049

Using radioList method with ActiveField in Yii2 to provide different options per radio box

I'm using the radioList method within the ActiveField widget and I'm trying to work out how to set different options for different radio boxes within the same list.

I have this...

$form->field($model, 'some_question')->inline()->radioList(
    [
        1 => Yii::t('general', 'Yes'),
        0 => Yii::t('general', 'No')
    ],
    ['itemOptions' => ['value' => 1, 'data-foo' => 'bar']]
)->label(false);

But whatever I set in itemOptions gets set on all radio buttons - is there a way to set different values for each one?

Upvotes: 1

Views: 576

Answers (1)

Bizley
Bizley

Reputation: 18021

Use callable item for this.

$form->field($model, 'some_question')->inline()->radioList(
    [
        1 => Yii::t('general', 'Yes'),
        0 => Yii::t('general', 'No')
    ],
    ['item' => function ($index, $label, $name, $checked, $value) {
        switch ($value) {
            // different options per value
            case 1:
                $options = [
                    'data-foo' => 'bar'
                ];
                break;
            case 0:
                $options = [
                    'data-next' => 'smthng'
                ];
        }
        return \yii\bootstrap\Html::radio($name, $checked, array_merge($options, [
                'value' => $value,
                'label' => \yii\bootstrap\Html::encode($label),
            ]));
    }]
)->label(false);

Upvotes: 1

Related Questions