Search code examples
phparraysyii2yii2-model

How to add different and common classes in radioList() in yii2


This is the chtml of radio-button in one of my update form.

 <?= $form->field($model, 'customer_sel')->radioList(array('customer' => 'Customer', 'supplier' => 'Supplier', 'excludecustomer' => 'Exclude Customer', 'all' => 'All'))->label('Select Choice'); ?>

I need to add class names of common(same) and different classes to each radio input. That is it look like in html...

 <div class="form-group field-cashbankentry-customer_sel">
<label class="control-label" for="cashbankentry-customer_sel">Select Choice</label>
<input type="hidden" name="CashBankentry[customer_sel]" value=""><div id="cashbankentry-customer_sel"><label><input type="radio" class="inputbox inputindex_1" name="CashBankentry[customer_sel]" value="customer" checked> Custom</label>
<label><input type="radio" class="inputbox inputindex_2 name="CashBankentry[customer_sel]" value="supplier"> Supplier</label>
<label><input type="radio" class="inputbox inputindex_3 name="CashBankentry[customer_sel]" value="excludecustomer"> Exclude Customer</label>
<label><input type="radio" class="inputbox inputindex_4 name="CashBankentry[customer_sel]" value="all"> All</label></div>

i have classes to add [inputbox(common to all)and inputindex_1-4 to each radios] i'm syntactically confused to add array of classes to this. How to add these classes to this

<?= $form->field($model, 'customer_sel')->radioList(array('customer' => 'Customer', 'supplier' => 'Supplier', 'excludecustomer' => 'Exclude Customer', 'all' => 'All'))->label('Select Choice'); ?>

Solution

  • You need to configure the item option for the radioList options, you can see the Html::activeRadioList() for details.

    The below code should work for you.

    <?php echo $form->field($model, 'customer_sel')->radioList(
            [
                'customer' => 'Customer',
                'supplier' => 'Supplier',
                'excludecustomer' => 'Exclude Customer',
                'all' => 'All',
            ],
            [
                'item' => function ($index, $label, $name, $checked, $value) {
    
                    $return = '<label>';
                    $return .= '<input class="inputbox inputindex_' . (++$index) . '" type="radio" name="' . $name . '" value="' . $value . '" ' . ($checked ? "checked" : "") . '>';
                    $return .= ucwords($label);
                    $return .= '</label>';
                    return $return;
                },
    
            ]
        )->label('Select Choice');
    ?>
    

    Note: to make the first option selected by default, you should set the attribute with the value inside the action. like

    $model = new CashBankentry();
    $model->customer_sel='customer';