如何在yii2下拉列表子菜单中创建?

时间:2016-11-21 05:43:32

标签: php html drop-down-menu yii2 html-select

我的yii2字段类下拉列表子菜单有问题吗? 如何在下拉列表子菜单或子选择列表中创建。enter image description here my form

我的数据库方案

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| group_name   | varchar(255) | NO   |     | NULL    |                |
| short_name   | varchar(32)  | NO   |     | NULL    |                |
| parent_group | int(11)      | YES  |     | NULL    |                |
| admin_group  | int(11)      | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
数据中的

+----+------------------------------------+------------+--------------+-------------+
| id | group_name                         | short_name | parent_group | admin_group |
+----+------------------------------------+------------+--------------+-------------+
|  1 | Jizzax Davlat Pedagogika instituti | JDPI       |         NULL |        NULL |
|  2 | O'quv ishlari bo'yicha Prorektor   | Prorektor  |            1 |        NULL |
|  3 | Axborot tehnologiyalari markazi    | ATM        |            2 |        NULL |
+----+------------------------------------+------------+--------------+-------------+

我使用short_name和echo select我看:

-JDPI 
--Prorektor
---ATM

1 个答案:

答案 0 :(得分:1)

将此方法添加到模型类

public static function getItems($indent = '', $parent_group = null)
{
    $items = [];
    // for all childs of $parent_group (roots if $parent_group == null)
    $groups = self::find()->where(['parent_group'=>$parent_group])
        ->orderBy('short_name')->all();
    foreach($groups as $group)
    {
        // add group to items list 
        $items[$group->id] = $indent.$group->short_name;
        // recursively add children to the list with indent
        $items = array_merge($items, self::getItems($indent.' ', $group->id));
    }
    return $items;
}

方法输出应为

[
    1 => 'JDPI',
    2 => ' Prorektor',
    3 => '  ATM'
]

在视图中

echo $form->field($model, 'group_id')->dropDownList(YourModelClass::getItems());

其中YourModelClass是您的模型类名称。

我建议使用嵌套集来存储树信息。嵌套集有一些扩展: