M
M
Michael2018-12-24 20:58:26
Yii
Michael, 2018-12-24 20:58:26

How can I make it so that the content of child categories is displayed when navigating through the parent element?

Hello everybody! Tell me how to make it so that when you click on the parent element, get the output of all the materials of the child categories? The code below is not written by me, but I use it to display the category menu, this code is written as a widget.

public $tpl;
    public $model;
    public $data;
    public $tree;
    public $menuHtml;

    public function init(){
        parent::init();
        if( $this->tpl === null ){
            $this->tpl = 'menu';
        }
        $this->tpl .= '.php';
    }

    public function run(){
        if($this->tpl == 'menu.php'){
            $menu = Yii::$app->cache->get('menu');
            if($menu) return $menu;
        }

        $this->data = Category::find()->indexBy('id')->orderBy('position')->asArray()->all();
        $this->tree = $this->getTree();
        $this->menuHtml = $this->getMenuHtml($this->tree);
        
        if($this->tpl == 'menu.php'){
            set cache
            Yii::$app->cache->set('menu', $this->menuHtml, 60);
        }

        return $this->menuHtml;
    }

    protected 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, $tab = ''){
        $str = '';
        foreach ($tree as $category) {
            $str .= $this->catToTemplate($category, $tab);
        }
        return $str;
    }

    protected function catToTemplate($category, $tab){
        ob_start();
        include __DIR__ . '/menu_tpl/' . $this->tpl;
        return ob_get_clean();
    }

The file responsible for displaying the category menu
<li>
  <a href="<?= \yii\helpers\Url::to(['category/view', 'alias_cat' => $category['alias']]) ?>">
  <?= $category['name'] ?>
  <?php if ( isset($category['childs']) ): ?>
    
  <?php endif; ?>
  </a>
  <?php if ( isset($category['childs']) ): ?>
    <ul>
      <?= $this->getMenuHtml($category['childs']) ?>
    </ul>
  <?php endif; ?>
</li>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question