I'm using Yii nested set behavior, which helps me to keep my categories nested as seen here (nevermind title rows, they are in russian):
And all I want to do is to have Bootstrap nested menu, which should be like this:
$criteria = new CDbCriteria;
$criteria->order = 'root, lft';
$categories = Category::model()->findAll($criteria);
foreach($categories as $i => $category) {
$items[$i]['label'] = $category->title;
$items[$i]['url'] = $category->url;
$items[$i]['active'] = false;
$items[$i]['items'] = array(
array('label'=>'123', 'url'=>'#'),
array('label'=>'123', 'url'=>'#'),
array('label'=>'123', 'url'=>'#', 'items'=>array(
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#', 'items'=>array(
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#'),
array('label'=>'1234', 'url'=>'#'),
)),
)),
);
}
$this->widget('bootstrap.widgets.TbMenu', array(
'type'=>'pills',
'stacked'=>false, // whether this is a stacked menu
'items'=>$items
));
I don't understand how to get this done, btw I read this topic and just don't know how actually apply this function to my problem. Appreciate any help.
Finally, my own recursive solution (works with multiple roots):
public function getTreeRecursive() {
$criteria = new CDbCriteria;
$criteria->order = 'root, lft';
$criteria->condition = 'level = 1';
$categories = Category::model()->findAll($criteria);
foreach($categories as $n => $category) {
$category_r = array(
'label'=>$category->title,
'url'=>'#',
'level'=>$category->level,
);
$this->category_tree[$n] = $category_r;
$children = $category->children()->findAll();
if($children)
$this->category_tree[$n]['items'] = $this->getChildren($children);
}
return $this->category_tree;
}
private function getChildren($children) {
$result = array();
foreach($children as $i => $child) {
$category_r = array(
'label'=>$child->title,
'url'=>'#',
);
$result[$i] = $category_r;
$new_children = $child->children()->findAll();
if($new_children) {
$result[$i]['items'] = $this->getChildren($new_children);
}
}
return $result_items = $result;
}