Add class active to menu item

Hello.

How to add a class active menu which has the form and cycle output from the database


<ul class="menu">

<li><a href="#">One Item</a></li>

<li><a href="#">Two Item</a></li>

<li><a href="#">Three Item</a></li>

</ul>

Thank you

Suppose your controller is ‘mycontroller’ and action is ‘myform’ (i.e. for url like /index.php?r=mycontroller/myform), try following code:




<ul class="menu">

<?php if(Yii::app()->controller->id == 'mycontroller'  && Yii::app()->controller->action->id == 'myform'):  ?>

      	<li class='active'><a href="#">One Item</a></li>

 <?php else: ?>

      	<li><a href="#">One Item</a></li>

 <?php endif; ?>

<?php if(Yii::app()->controller->id == 'mycontroller'  && Yii::app()->controller->action->id == 'myform'):  ?>

 		<li class='active'><a href="#">One Item</a></li>

 <?php else: ?>

      	<li><a href="#">Two Item</a></li>

 <?php endif; ?>

...

...

</ul>



  1. when controller - site and action - index, menu always highlighted

if(Yii::app()->controller->id == 'site'  && Yii::app()->controller->action->id == 'index')

  1. Each controller will have to register separately? and if they are 20 pieces or more?

isItemActive does not help in my case?

Hi you can make use of the CMenu widget it gives you that functionality out of the box

http://www.yiiframework.com/doc/api/1.1/CMenu/

Please check wiki, may be helpful for you.

One another solution is extending CMenu and creating custom menu… But how could you create menu, Please provide some code…

Here is my menu. What advise do in this case? About CMenu of course I know, but it’s not my variant


function menu($value) {

    echo '<ul>';

    foreach ($menus as $menu) {

        echo '<li><a href=' . $menu[link] . '>' . $menu[text] . '</a></li>';

    }

    echo '</ul>';

}

Please provide your ‘$menu[link]’ data also…

links as Yii


http://site.com/index.php?r=site/contact 

or normal


http://www.google.com/

For links as YII use following code:





/*

 * for http://site.com/index.php?r=site/contact 

 * Yii::app()->controller->route gives us "site/contact"

 */

function menu($value) {

	echo '<ul>';

	foreach ($menus as $menu) {

    	if(strpos($menu[link], Yii::app()->controller->route) === false){

        	echo '<li><a href=' . $menu[link] . '>' . $menu[text] . '</a></li>';        	

    	}

    	else{

        	echo '<li class="active"><a href=' . $menu[link] . '>' . $menu[text] . '</a></li>';        	

    	}

	}

	echo '</ul>';

}



For external links (like www.goolge.com) we can’t do anything, because there are nothing to showing for this menu item.

But I thinks that using CMenu is best way of creating menus in YII.

Hope it will help you…

Thanks, it’s work!