如何查询yii中多级菜单的情况?
例如,我有一个这样的表:
menu_name
会跟随它parrent_id
,因此会形成hierarchical
菜单
如何在布局上使用Yii
,以便输出为上面的html
我的代码:
<?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();
}
}
但在上面的代码中我只得到parents data
。我如何循环以在每个父母菜单中获取childs data
包括此html代码:
<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>
由于
答案 0 :(得分:1)
您可以创建一个递归函数来循环您的孩子,就像这样
<?php
class ActiveMenu extends CMenu
{
public function init(){
$this->renderChilds();
}
protected function getChilds($parent_id)
{
$criteria = new CDbCriteria;
$criteria->condition='published=:idpub AND menu_controller=:menu AND parent_id = :parent';
$criteria->params=array(':idpub'=>1, ':menu'=>'#', ':parent'=>$parent_id);
$items = Menu::model()->findAll($criteria);
return $items;
}
public function renderChilds($parent_id=0, $class='nav')
{
$items = $this->getChilds($parent_id);
if (!empty($items))
{
echo "<ul class='$class'>";
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>";
$this->renderChilds($item->id, 'dropdown-menu');
echo "</li>";
}
echo "</ul>";
}
}
...
}