A
A
Alexander Gorkin2018-07-23 15:28:48
Yii
Alexander Gorkin, 2018-07-23 15:28:48

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;?>

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
5b55cab82f3fb097759189.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-07-23
@mrbagfreeman

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 question

Ask a Question

731 491 924 answers to any question