Answer the question
In order to leave comments, you need to log in
When deriving name from the category table, an error is thrown. How to fix?
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;?>
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();
}
}
Answer the question
In order to leave comments, you need to log in
Syntax error, if it is an array, then it looks like this;
if an object , then it looks like this
. And you have something in between and the error indicates this to you.
offtopic: do not climb into the database from the widget. The widget should not know that you have a database at all, it should receive an array of data, and your code
should be somewhere in the controller and probably be cached so as not to pull the same thing all the time
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question