'items'=>array(
array(
'label'=>'About',
'url'=>array('about/index')
),
about/index
- we get the class on the menu - active.
about/graphic
- we don't get the class on the menu active.
about/print
- we don't get the class on the menu active.
Please note that the menu has NO subitems.
Only About.
No mater if the user is on graphic, print or whatever, we wish to have the About highlighted.
How can we accomplish this ?
I've tried to edit that 'url' param a lot. No luck.
'items'=>array(
array(
'label'=>'About',
'url'=>array('about/index'),
'active'=>Yii::app()->controller->id=='about',
),
Added the active
param. This worked.
active: boolean, optional, whether this menu item is in active state
(currently selected). If a menu item is active and activeClass is not
empty, its CSS class will be appended with activeClass. If this option
is not set, the menu item will be set active automatically when the
current request is triggered by url. Note that the GET parameters
not specified in the 'url' option will be ignored.
I've set that property. Otherwise it wouldn't work.
However, as you can see on the bold line, they say this should be automatically triggered. It wasn't on this case.
I suppose this was the case due to the fact that Yii is expecting a child element of About in order to apply that class, since there's any, we have to force it, to get the parent instead.
Not sure however.
CMenu is comparing item's route to current route, so by default it will work only for about/index
.
I see two ways of forcing it - first is just set 'active' => true
in items list:
$isActive = strpos(Yii::app()->controller->route, 'about/') === 0;
// ....
'items'=>array(
array(
'label'=>'About',
'url'=>array('about/index'),
'active' => $isActive
),
Or you can subclass CMenu class and overwrite CMenu::isItemActive($item,$route)
method
simple but effective:
$action = Yii::app()->controller->action->id; // this is the action name currently running
'items'=>array(
array(
'label'=>'About',
'url'=>'/about/something',
'active'=>$action == 'something',
),
also...
to activate a menu, regardless of the action, just for a controller:
$controller = Yii::app()->controller->id; // this is the controller name
...
'active'=>$controller == 'something',
Notes:
add the $controller or $action variables, you can use them for more menu items. Your code will be cleaner.
you'll be 100% sure, the menu items will 'stick' active