В виджете нужно вывести дерево массива. Вот сам виджет:
<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;?>
Компонент виджета:
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();
}
}
Ошибка