自定义数据属性需要使用Yii2的动态值

时间:2017-03-14 11:27:42

标签: yii2

使用Yii2 Framework,从ArrayHelper::map()获取数据,我无法获取动态数据

<input class="services-checkbox" name="SubscriptionPackage[services][]" value="1" data-serviceid="id" type="checkbox">
<input class="services-checkbox" name="SubscriptionPackage[services][]" value="2" data-serviceid="id" type="checkbox">
<input class="services-checkbox" name="SubscriptionPackage[services][]" value="3" data-serviceid="id" type="checkbox">
 <?= $form->field($model, 'services')->checkboxList(ArrayHelper::map($activeServiceModels, 'id', 'name'), ['itemOptions' => ['class' => 'services-checkbox','data-serviceid'=>'id']])->label('Select Service(s):'); ?>

我需要输出

<input class="services-checkbox" name="SubscriptionPackage[services][]" value="1" data-serviceid="1" type="checkbox">
<input class="services-checkbox" name="SubscriptionPackage[services][]" value="1" data-serviceid="2" type="checkbox">
<input class="services-checkbox" name="SubscriptionPackage[services][]" value="1" data-serviceid="3" type="checkbox">

2 个答案:

答案 0 :(得分:1)

更新您的代码,如下所示

<?=
  $form->field($model, 'services')->checkboxList(ArrayHelper::map($activeServiceModels, 'id', 'name'), ['class'=>"btn-checkbox",
    'item' => function($index, $label, $name, $checked, $value) {
        return "<label class='col-md-4'><input type='checkbox' data-serviceid="1" {$checked} name='{$name}' value='{$value}'>{$label}</label>";
    }
 ]);
 ?>

将您的班级“class”=&gt;“btn-checkbox”添加到数组中。

您可以在项目回调函数内调试更多以进行自定义。

答案 1 :(得分:1)

您可以使用项目可调用函数来呈现每个复选框项目,例如:

$form->field($model, 'name')->checkboxList(ArrayHelper::map($models, 'id', 'name'), [
    'itemOptions' => ['class' => 'services-checkbox','data-serviceid'=>'id'],
    'item' => function ($index, $label, $name, $checked, $value) {
        return Html::checkbox($name, $checked, ['data-serviceid' => $value, 'value' => 1]) . Html::label($label);
    }
])->label('Select Service(s):');