Reputation: 1601
How do I do a query to the case of multi-level menus in yii?
For example I have a table like this :
menu_name
will follow parrent_id
it has, so it will form a hierarchical menu
How do I use Yii DAO
on my layout so that the output as html above
My Code :
<?php
Yii::import('zii.widgets.CMenu', true);
class ActiveMenu extends CMenu
{
public function init(){
$criteria = new CDbCriteria;
$criteria->condition='published=:idpub AND menu_controller=:menu';
$criteria->params=array(':idpub'=>1, ':menu'=>'#');
$items = Menu::model()->findAll($criteria);
echo "<ul id='yw1' class='nav'>";
foreach ($items as $item)
{
echo "<li class='dropdown'>
<a href=".$item->menu_controller." data-toggle='dropdown' class='dropdown-toggle'>
<i class='icon-white icon-list'></i>".$item->menu_name."<b class='caret'></b></a>
</li>";
}
echo "</ul>";
parent::init();
}
}
But in the above code I only get parents data
. How do I want to loop to get the childs data
include in every parents menu like this html code :
<ul id="yw1" class="nav">
<li><a href="/app/home.html"><span class="icon-white icon-tasks"></span> Home</a></li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">
<i class="icon-white icon-list"></i>Master<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="expedition"><span class="icon-bar icon-list"></span> Expedition</a></li>
</ul>
<ul class="dropdown-menu">
<li><a href="partner"><span class="icon-bar icon-list"></span> Partner</a></li>
</ul>
<ul class="dropdown-menu">
<li><a href="user"><span class="icon-bar icon-list"></span> User</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">
<i class="icon-white icon-list"></i>Transaction<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="processin"><span class="icon-bar icon-list"></span> Process In</a></li>
</ul>
<ul class="dropdown-menu">
<li><a href="processout"><span class="icon-bar icon-list"></span> Process Out</a></li>
</ul>
etc ....
etc ....
etc ....
</li>
</ul>
Upvotes: 3
Views: 2330
Reputation: 809
You should first have the relations set up properly in your Menu
model (Menu.php).
public function relations()
{
return array(
'parent' => array(self::BELONGS_TO, 'Menu', 'parent_id'),
'children' => array(self::HAS_MANY, 'Menu', 'parent_id'),
);
}
And then modify the codes:
//other codes
foreach ($items as $item)
{
echo "<li class='dropdown'>
<a href=".$item->menu_controller." data-toggle='dropdown' class='dropdown-toggle'>
<i class='icon-white icon-list'></i>".$item->menu_name."<b class='caret'></b></a>
</li>";
foreach ($item->children as $child) {
echo "<ul class='dropdown-menu'>
<li><a href='".$child->menu_controller."'><span class='icon-bar icon-list'></span> ".$child->menu_name."</a></li></u>";
}
}
//other codes
Upvotes: 1