Skip to content

Instantly share code, notes, and snippets.

@ale10257
Last active August 31, 2020 11:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ale10257/19fa0f0e20569a83e15e1e43179e7121 to your computer and use it in GitHub Desktop.
Save ale10257/19fa0f0e20569a83e15e1e43179e7121 to your computer and use it in GitHub Desktop.
Yii2 displaying a menu with an unlimited nesting level from Nested Sets
<?php
/**
* @var $this yii\web\View
* @var $categories \app\models\Category[]
* @var $level_start int
*/
use yii\helpers\Html;
/**
* Displaying a menu with an unlimited nesting level from Nested Sets
* ported code for yii2 from https://github.com/yiiext/nested-set-behavior/blob/master/readme_ru.md#%D0%9E%D0%B1%D1%85%D0%BE%D0%B4-%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0-%D0%B1%D0%B5%D0%B7-%D1%80%D0%B5%D0%BA%D1%83%D1%80%D1%81%D0%B8%D0%B8
*
* example:
*
* $root_node = Category::find()->where(['depth' => 0])->one();
* $level_start = $root_node->depth;
* $categories = $root_node->children()->all();
* return $this->render('sidebar', ['categories' => $categories, 'level_start' => $level_start]);
*
*/
$level = $level_start;
$menu = null;
foreach ($categories as $key => $category) {
switch ($category->depth) {
case ($category->depth == $level):
$menu .= Html::endTag('li') . PHP_EOL;
break;
case $category->depth > $level:
$class_ul = $level == $level_start ? 'main-menu' : 'sub-menu';
$menu .= Html::beginTag('ul', ['class' => $class_ul]);
break;
case $category->depth < $level:
$menu .= Html::endTag('li') . PHP_EOL;
for ($i = $level - $category->depth; $i; $i--) {
$menu .= Html::endTag('ul') . PHP_EOL;
$menu .= Html::endTag('li') . PHP_EOL;
}
break;
};
//If you do not need to add a class to the parent tag li
$menu .= Html::beginTag('li');
$menu .= Html::a($category->name, '#');
//if you want to add a class to the parent tag li uncomment this block && comment prev block
/*if (isset($categories[$key + 1]) && $categories[$key + 1]->depth > $category->depth) {
$menu .= Html::beginTag('li', ['class' => 'parent']);
$menu .= Html::a($category->name, '/category');
} else {
$menu .= Html::beginTag('li');
$menu .= Html::a($category->name, '/sub-category');
}*/
$level = $category->depth;
}
for ($i = $level; $i > $level_start; $i--) {
$menu .= Html::endTag('li') . PHP_EOL;
$menu .= Html::endTag('ul') . PHP_EOL;
}
echo $menu;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment