2

Here is the sample code from Yii2 checkboxList, I want to add custom class for each Item in checkboxList but I don't know how and where can I add that!
Could you please help me please ..

$list = [0 => 'PHP', 1 => 'MySQL', 2 => 'Javascript'];
$list2 = [0,2];

echo Html::checkboxList('CuisineId',$list2,$list,array('class' => 'test' ));

Thanks in advance.

2 Answers 2

9

If you want to add the same class, you should use itemOptions :

echo Html::checkboxList('CuisineId', $list2, $list, ['itemOptions'=>['class' => 'test']]);

Or if you want a custom class for each item, you should use item callback :

echo Html::checkboxList('CuisineId', $list2, $list, ['item'=>function ($index, $label, $name, $checked, $value){
    return Html::checkbox($name, $checked, [
       'value' => $value,
       'label' => $label,
       'class' => 'any class',
    ]);
}]);

Read more : http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#checkboxList()-detail

EDIT : add example

Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much for your current replay , but could please give me a sample to do work with this function ? I saw this yesterday in yii2 API documents.. I just want to add different classes to each Item .. I have to write custom function for each item ? just let me know how to add class to for each Item.. thank you so much for your great replay .
You only need one function, take a look at my example and docs. And I can't guess what is behind "I just want to add different classes to each Item".
very nice! I used $index variable to creating custom class name ! thank you so much ! " 'class' => 'woshiClass'.$index,"
3

Just in case you only need to change the label options:

<?= Html::checkboxList('CuisineId', $list, $items, [
    'itemOptions' => [
        'labelOptions' => [
            'style' => 'font-weight: normal',
            'class' => 'some-custom-class',
        ],
    ],
]) ?>

Note: Everything you put inside itemOptions will be passed to Html::checkbox() as its own options when creating each checkbox. It means you can pass class, style, label, labelOptions, etc.

1 Comment

This working fine for applying styles for checkbox labels. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.