2016-11-21 44 views
1

我有yii2字段類dropdownlist子菜單的問題? 如何在下拉列表子菜單或子選擇列表中創建。 enter image description here my form如何在yii2下拉列表子菜單中創建?

我的DB計劃

+--------------+--------------+------+-----+---------+----------------+ 
| 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和回聲選擇我看到:

-JDPI 
--Prorektor 
---ATM 
+0

出於什麼目的,你想用它?是否用於導航? –

+0

使用獲取ID選擇項目 – DasturchiUZ

+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是模型類的名字。

我建議使用嵌套組存儲樹information.There一些擴展嵌套組:

+0

感謝代碼工作 – DasturchiUZ