Create a dynamic SideNav Widget

What is the correct way to dynamically create a menu using the "SideNav Widget" and 2 models the following:

category (id, description)

subcat (id, category_id, description)

Follow the desired structure:


	<?php


	echo SideNav::widget([

    	//'type' => SideNav::TYPE_DEFAULT,

    	//'heading' => 'Options',

    	'items' => [

        	[

            	'url' => '#',

            	'label' => 'Category One',

            	'items' => [

                	['label' => 'Sub-Category 1.1', 'url'=>'#'],

                	['label' => 'Sub-Category 1.2', 'url'=>'#'],

            	],

        	],

        	[

            	'label' => 'Category Two',

            	'items' => [

                	['label' => 'Sub-Category 2.1', 'url'=>'#'],

                	['label' => 'Sub-Category 1.1', 'url'=>'#'],

            	],

        	],

    	],

	]);  	

	?>

EDIT

The first loop in CATEGORY works fine.


$item = [];

    	$models = Category::find()->all();

    	foreach($models as $model) {

        	$item[] = ['label' => $model->description, 'url' => '#'];

}

How to make a loop (to get the subcat) within this other?

You can use "Recursive Algorithm"

You only need one table for store multiple level categories

The table construct

Category(id,name,parentId)

See the below code snippet


function getSubCategories($parentCategory){    

    $subCategories = Category::find(['parentId'=>$parentCategory->id])->all();

    if(count($subCategories)>0){

        return $subCategories;

    }else{

        return null;

    }

}


function getItems($category){  

   $subCategories = getSubCategories($category);


   if($subCategories==null){

      // Have no subcategory, so just return single item

      $item = ['label' => $category->name, 'url'=>'...'];

   }else{

      // Get all sub items and return

      $subItems = [];

      foreach ($subCategories as $subcategory) {

          $subItems[] = getItems($subcategory);

      }

      $item = ['label' => $category->name, 'url'=>'...', 'items'=>$subItems];

   }

   return $item;

}


$items = [];

$rootCategories = Category::find(['parentId'=>'null'])->all();

foreach($rootCategories as $rootCategory) {

     $items[] = $getItems($rootCategory);


echo SideNav::widget([    

        // nav options    

        'items' => $items,

        ]);     

I hope this useful for you :rolleyes:

Hi John,

I get this error:

[b]PHP Fatal Error – yii\base\ErrorException

Maximum function nesting level of ‘100’ reached, aborting![/b]

(just 3 categories parent in DB)