In the widget you need to display an array tree. Here is the widget itself:

<li> <a href=""> <?= $category->['name']?> <?php if (isset($category['childs'])):?> <span class="badge pull-right"><i class="fa fa-plus"></i></span> <?php endif;?> </a> <?php if( isset($category['childs'])):?> <ul> <?= $this->getMenuHtml($category['childs'])?> </ul> <?php endif;?> 

Widget component:

 namespace app\components; use app\models\Category; use yii\base\Widget; class MenuWidget extends Widget{ public $tpl; public $data; public $menuHtml; public $tree; public function init() { parent::init(); if ( $this->tpl === null) { $this->tpl = 'menu'; } $this->tpl .= '.php'; } public function run(){ $this->data = Category::find()->indexBy('id')->asArray()->all(); $this->tree=$this->getTree(); $this->menuHtml = $this->getMenuHTML($this->tree); return $this->menuHtml; } public function getTree() { $tree = []; foreach ($this->data as $id=>&$node) { if (!$node['parent_id']) $tree[$id] = &$node; else $this->data[$node['parent_id']]['childs'][$node['id']]=&$node; } return $tree; } protected function getMenuHTML($tree) { $str = ''; foreach ($tree as $category) { $str .= $this->catToTemplate($category); } return $str; } protected function catToTemplate( $category ) { ob_start(); include __DIR__ . '/menu_tpl/' . $this->tpl; return ob_get_clean(); } } 

Mistake: enter image description here

  • $category->name - Anton Kucenko

1 answer 1

Mistake in:

 <?= $category->['name']?> 

Must be either

 <?= $category['name']?> 

if it is an array or

 <?= $category->{'name'}?> <?= $category->name?> 

if this is an object field