Dynamic Multilevel Drop-down menu in Yii2

user3265065 picture user3265065 · Jun 4, 2014 · Viewed 9.2k times · Source

I want to create a dynamic menu with my table (db). I have followed some instructions which are given below:

Table : "menupanal"

Table : "menupanal"

Step 01: I just create a super controller in app\components\Controller.php

Here is the code:

    namespace app\components;

use app\models\MenuPanal;

class Controller extends \yii\web\Controller
{

    public $menuItems = [];

    public function init(){

     $items = MenuPanal::find()
        ->where(['c_type'  => 'MENU'])
        ->orderBy('id')
        ->all();


     $menuItems = [];
     foreach ($items as $key => $value) {
                 $this->menuItems[] = 
                      ['label' => $value['c_name'], 
                          'items'=> [
                              ['label' => $value['c_redirect'], 'url' => ['#']],
                          ],
                      ];    
            }

  parent::init();
}

Step 02: Changed n main layout page:

        echo Nav::widget([
            'options' => ['class' => 'navbar-nav navbar-right'],

            'items' => Yii::$app->controller->menuItems,
        ]);

It is working in only one level. My question::

Question : how can I add multilevel menu using Super controller ?

I am new in Yii2. Helps are highly appreciated.

Answer

kayakkamil picture kayakkamil · Jun 4, 2014

You may use nested sets. Look at this extension for Yii: http://www.yiiframework.com/extension/nestedsetbehavior/ and its documentation. All you need to do is component with dynamic creation of menu items array for nested sets.

I found that there is a Yii2 extension version: http://www.yiiframework.com/extension/yii2-nestedsetbehavior/

Good luck