具有动态项目的Yii2 Dropdown小部件

时间:2016-03-21 07:20:30

标签: yii2 dropdown

我想在yii2中使用动态项目的下拉小部件。这怎么可能? 这样做后,我面临一个错误,该选项是必需的。 我的代码有什么问题?

$items = [];
foreach ($all_label as $each_label) {               

      $items[$each_label->id_label]['id_label'] = $each_label->id_label;
      $items[$each_label->id_label]['label'] = $each_label->label_name;
}
print_r($items);

O:P-

Array
(
[5] => Array
    (
        [id_label] => 5
        [label] => Label1
    )

[6] => Array
    (
        [id_label] => 6
        [label] => Label2
    )

[9] => Array
    (
        [id_label] => 9
        [label] => Label3
    )

)       

echo Dropdown::widget([
    'items' => [
                $items
            ],                                     
    ]);

1 个答案:

答案 0 :(得分:0)

好的,检查规格后,问题似乎是你使用" id_label"这不是小部件的有效选项。 你需要把它留下来:

$items = [];
foreach ($all_label as $each_label) {               
     $items[$each_label->id_label]['label'] = $each_label->label_name;
}

如果这不能根据您的需要生成值,请尝试适应:

$items = [];
foreach ($all_label as $each_label) {               
     $items[$each_label->id_label]['label'] = $each_label->label_name;
     $items[$each_label->id_label]['options']['value'] = $each_label->id_label_;
}

http://www.yiiframework.com/doc-2.0/yii-bootstrap-dropdown.html# $项细节