Yii2 ActiveForm自定义模板的复选框字段

时间:2016-10-20 12:13:35

标签: templates yii2 checkboxlist

我正在寻找使用checkboxList的模板。 那是我想申请的属性

class =“switch”checked data-on-text =“ON”data-off-text =“OFF”data-on-color =“teal”

<?php $form = ActiveForm::begin(); ?> 
                            <ul class="list-unstyled">
                                <li>
                                    <?= $form->field($modelUserPermission, 'id_permission')->checkboxList(ArrayHelper::map(Permission::find()->all(),'id', 'code')) ?>
                                </li><br>  
                           </ul>
                        <div class="form-group">
                            <?= Html::submitButton($modelUserPermission->isNewRecord ? 'Create' : 'Update', ['class' => $modelUserPermission->isNewRecord ? 'btn btn-success' : 'btn btn-primary', 'value'=>'Create', 'name'=>'submit']) ?>
                        </div>
                    <?php ActiveForm::end(); ?>

3 个答案:

答案 0 :(得分:1)

Bizley 提供的答案是正确的,但如果您愿意,可以尝试另外一种方法。

<?php 
    $items_array = ArrayHelper::map(Permission::find()->all(),'id', 'code');

    echo $form->field($model, 'id_permission')->checkboxList($items_array, [
        'items' =>
        function ($index, $label, $name, $checked, $value) {
            return Html::checkbox($name, $checked, [
                        'value' => $value,
                        'label' => '<label for="' . $label . '">' . $label . '</label>',
                        'labelOptions' => [
                        // you can set label options here                                                ],
                        ],
            ]);
        }, 'itemOptions' => ['class' => 'switch',
                    'data-on-text' => 'ON', 'data-off-text' => 'OFF', 'data-on-color' => 'teal'],
                'separator' => false,]);
?>

答案 1 :(得分:0)

<?= $form->field($model, 'recomended_by_user', ['template'=>'<div class="control-group">
                                <label class="control control--checkbox checkbox-small-text">Recomended by user
                                    {input}
                                    <div class="control__indicator"></div>
                                </label>
                            </div>'])->textInput(['class'=>"",'type'=>'checkbox'])?>

像这样用于自定义复选框模板

答案 2 :(得分:-1)

If you want these properties in every checkbox (like Insane Skull asked) use itemOptions option.

<?= $form->field($modelUserPermission, 'id_permission')->checkboxList(
    ArrayHelper::map(Permission::find()->all(),'id', 'code'),
    [
        'itemOptions' => [
            'class' => 'switch',
            'data' => [
                'on-text' => 'ON',
                'off-text' => 'OFF',
                'on-color' => 'teal'
            ],
        ],
    ]
) ?>

Since it's ActiveField widget in order to get all checkboxes checked you have to pass array to $modelUserPermission->id_permission with all the IDs.