Versions
Look up a class, method, property or event

CMenu

Package zii.widgets
Inheritance class CMenu » CWidget » CBaseController » CComponent
Since 1.1
Source Code framework/zii/widgets/CMenu.php
CMenu displays a multi-level menu using nested HTML lists.

The main property of CMenu is items, which specifies the possible items in the menu. A menu item has three main properties: visible, active and items. The "visible" property specifies whether the menu item is currently visible. The "active" property specifies whether the menu item is currently selected. And the "items" property specifies the child menu items.

The following example shows how to use CMenu:
$this->widget('zii.widgets.CMenu', array(
    'items'=>array(
        // Important: you need to specify url as 'controller/action',
        // not just as 'controller' even if default acion is used.
        array('label'=>'Home', 'url'=>array('site/index')),
        // 'Products' menu item will be selected no matter which tag parameter value is since it's not specified.
        array('label'=>'Products', 'url'=>array('product/index'), 'items'=>array(
            array('label'=>'New Arrivals', 'url'=>array('product/new', 'tag'=>'new')),
            array('label'=>'Most Popular', 'url'=>array('product/index', 'tag'=>'popular')),
        )),
        array('label'=>'Login', 'url'=>array('site/login'), 'visible'=>Yii::app()->user->isGuest),
    ),
));

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
actionPrefix string the prefix to the IDs of the actions. CWidget
activateItems boolean whether to automatically activate items according to whether their route setting matches the currently requested route. CMenu
activateParents boolean whether to activate parent menu items when one of the corresponding child menu items is active. CMenu
activeCssClass string the CSS class to be appended to the active menu item. CMenu
controller CController Returns the controller that this widget belongs to. CWidget
encodeLabel boolean whether the labels for menu items should be HTML-encoded. CMenu
firstItemCssClass string the CSS class that will be assigned to the first item in the main menu or each submenu. CMenu
hideEmptyItems boolean whether to hide empty menu items. CMenu
htmlOptions array HTML attributes for the menu's root container tag CMenu
id string Returns the ID of the widget or generates a new one if requested. CWidget
itemCssClass string the CSS class that will be assigned to every item. CMenu
itemTemplate string the template used to render an individual menu item. CMenu
items array list of menu items. CMenu
lastItemCssClass string the CSS class that will be assigned to the last item in the main menu or each submenu. CMenu
linkLabelWrapper string the HTML element name that will be used to wrap the label of all menu links. CMenu
linkLabelWrapperHtmlOptions array HTML attributes for the links' wrap element specified in linkLabelWrapper. CMenu
owner CBaseController Returns the owner/creator of this widget. CWidget
skin mixed the name of the skin to be used by this widget. CWidget
viewPath string Returns the directory containing the view files for this widget. CWidget

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CWidget
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
actions() Returns a list of actions that are used by this widget. CWidget
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
beginCache() Begins fragment caching. CBaseController
beginClip() Begins recording a clip. CBaseController
beginContent() Begins the rendering of content that is to be decorated by the specified view. CBaseController
beginWidget() Creates a widget and executes it. CBaseController
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
createWidget() Creates a widget and initializes it. CBaseController
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
endCache() Ends fragment caching. CBaseController
endClip() Ends recording a clip. CBaseController
endContent() Ends the rendering of content. CBaseController
endWidget() Ends the execution of the named widget. CBaseController
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getController() Returns the controller that this widget belongs to. CWidget
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getId() Returns the ID of the widget or generates a new one if requested. CWidget
getOwner() Returns the owner/creator of this widget. CWidget
getViewFile() Looks for the view script file according to the view name. CWidget
getViewPath() Returns the directory containing the view files for this widget. CWidget
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Initializes the menu widget. CMenu
raiseEvent() Raises an event. CComponent
render() Renders a view. CWidget
renderFile() Renders a view file. CBaseController
renderInternal() Renders a view file. CBaseController
run() Calls renderMenu to render the menu. CMenu
setId() Sets the ID of the widget. CWidget
widget() Creates a widget and executes it. CBaseController

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
isItemActive() Checks whether a menu item is active. CMenu
normalizeItems() Normalizes the items property so that the 'active' state is properly identified for every menu item. CMenu
renderMenu() Renders the menu items. CMenu
renderMenuItem() Renders the content of a menu item. CMenu
renderMenuRecursive() Recursively renders the menu items. CMenu

Property Details

activateItems property (available since v1.1.3)
public boolean $activateItems;

whether to automatically activate items according to whether their route setting matches the currently requested route. Defaults to true.

activateParents property
public boolean $activateParents;

whether to activate parent menu items when one of the corresponding child menu items is active. The activated parent menu items will also have its CSS classes appended with activeCssClass. Defaults to false.

activeCssClass property
public string $activeCssClass;

the CSS class to be appended to the active menu item. Defaults to 'active'. If empty, the CSS class of menu items will not be changed.

encodeLabel property
public boolean $encodeLabel;

whether the labels for menu items should be HTML-encoded. Defaults to true.

firstItemCssClass property (available since v1.1.4)
public string $firstItemCssClass;

the CSS class that will be assigned to the first item in the main menu or each submenu. Defaults to null, meaning no such CSS class will be assigned.

hideEmptyItems property
public boolean $hideEmptyItems;

whether to hide empty menu items. An empty menu item is one whose 'url' option is not set and which doesn't contain visible child menu items. Defaults to true.

htmlOptions property
public array $htmlOptions;

HTML attributes for the menu's root container tag

itemCssClass property (available since v1.1.9)
public string $itemCssClass;

the CSS class that will be assigned to every item. Defaults to null, meaning no such CSS class will be assigned.

itemTemplate property (available since v1.1.1)
public string $itemTemplate;

the template used to render an individual menu item. In this template, the token "{menu}" will be replaced with the corresponding menu link or text. If this property is not set, each menu will be rendered without any decoration. This property will be overridden by the 'template' option set in individual menu items via {@items}.

items property
public array $items;

list of menu items. Each menu item is specified as an array of name-value pairs. Possible option names include the following:

  • label: string, optional, specifies the menu item label. When encodeLabel is true, the label will be HTML-encoded. If the label is not specified, it defaults to an empty string.
  • url: string or array, optional, specifies the URL of the menu item. It is passed to CHtml::normalizeUrl to generate a valid URL. If this is not set, the menu item will be rendered as a span text.
  • visible: boolean, optional, whether this menu item is visible. Defaults to true. This can be used to control the visibility of menu items based on user permissions.
  • items: array, optional, specifies the sub-menu items. Its format is the same as the parent items.
  • 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.
  • template: string, optional, the template used to render this menu item. When this option is set, it will override the global setting itemTemplate. Please see itemTemplate for more details. This option has been available since version 1.1.1.
  • linkOptions: array, optional, additional HTML attributes to be rendered for the link or span tag of the menu item.
  • itemOptions: array, optional, additional HTML attributes to be rendered for the container tag of the menu item.
  • submenuOptions: array, optional, additional HTML attributes to be rendered for the container of the submenu if this menu item has one. When this option is set, the submenuHtmlOptions property will be ignored for this particular submenu. This option has been available since version 1.1.6.

lastItemCssClass property (available since v1.1.4)
public string $lastItemCssClass;

the CSS class that will be assigned to the last item in the main menu or each submenu. Defaults to null, meaning no such CSS class will be assigned.

linkLabelWrapper property (available since v1.1.4)
public string $linkLabelWrapper;

the HTML element name that will be used to wrap the label of all menu links. For example, if this property is set as 'span', a menu item may be rendered as <li><a href="url"><span>label</span></a></li> This is useful when implementing menu items using the sliding window technique. Defaults to null, meaning no wrapper tag will be generated.

linkLabelWrapperHtmlOptions property (available since v1.1.13)
public array $linkLabelWrapperHtmlOptions;

HTML attributes for the links' wrap element specified in linkLabelWrapper.

public array $submenuHtmlOptions;

HTML attributes for the submenu's container tag.

Method Details

init() method
public void init()
Source Code: framework/zii/widgets/CMenu.php#152 (show)
public function init()
{
    if(isset(
$this->htmlOptions['id']))
        
$this->id=$this->htmlOptions['id'];
    else
        
$this->htmlOptions['id']=$this->id;
    
$route=$this->getController()->getRoute();
    
$this->items=$this->normalizeItems($this->items,$route,$hasActiveChild);
}

Initializes the menu widget. This method mainly normalizes the items property. If this method is overridden, make sure the parent implementation is invoked.

isItemActive() method
protected boolean isItemActive(array $item, string $route)
$item array the menu item to be checked
$route string the route of the current request
{return} boolean whether the menu item is active
Source Code: framework/zii/widgets/CMenu.php#309 (show)
protected function isItemActive($item,$route)
{
    if(isset(
$item['url']) && is_array($item['url']) && !strcasecmp(trim($item['url'][0],'/'),$route))
    {
        unset(
$item['url']['#']);
        if(
count($item['url'])>1)
        {
            foreach(
array_splice($item['url'],1) as $name=>$value)
            {
                if(!isset(
$_GET[$name]) || $_GET[$name]!=$value)
                    return 
false;
            }
        }
        return 
true;
    }
    return 
false;
}

Checks whether a menu item is active. This is done by checking if the currently requested URL is generated by the 'url' option of the menu item. Note that the GET parameters not specified in the 'url' option will be ignored.

normalizeItems() method
protected array normalizeItems(array $items, string $route, boolean &$active)
$items array the items to be normalized.
$route string the route of the current request.
$active boolean whether there is an active child menu item.
{return} array the normalized menu items
Source Code: framework/zii/widgets/CMenu.php#261 (show)
protected function normalizeItems($items,$route,&$active)
{
    foreach(
$items as $i=>$item)
    {
        if(isset(
$item['visible']) && !$item['visible'])
        {
            unset(
$items[$i]);
            continue;
        }
        if(!isset(
$item['label']))
            
$item['label']='';
        if(
$this->encodeLabel)
            
$items[$i]['label']=CHtml::encode($item['label']);
        
$hasActiveChild=false;
        if(isset(
$item['items']))
        {
            
$items[$i]['items']=$this->normalizeItems($item['items'],$route,$hasActiveChild);
            if(empty(
$items[$i]['items']) && $this->hideEmptyItems)
            {
                unset(
$items[$i]['items']);
                if(!isset(
$item['url']))
                {
                    unset(
$items[$i]);
                    continue;
                }
            }
        }
        if(!isset(
$item['active']))
        {
            if(
$this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item,$route))
                
$active=$items[$i]['active']=true;
            else
                
$items[$i]['active']=false;
        }
        elseif(
$item['active'])
            
$active=true;
    }
    return 
array_values($items);
}

Normalizes the items property so that the 'active' state is properly identified for every menu item.

renderMenu() method
protected void renderMenu(array $items)
$items array menu items. Each menu item will be an array with at least two elements: 'label' and 'active'. It may have three other optional elements: 'items', 'linkOptions' and 'itemOptions'.
Source Code: framework/zii/widgets/CMenu.php#175 (show)
protected function renderMenu($items)
{
    if(
count($items))
    {
        echo 
CHtml::openTag('ul',$this->htmlOptions)."\n";
        
$this->renderMenuRecursive($items);
        echo 
CHtml::closeTag('ul');
    }
}

Renders the menu items.

renderMenuItem() method (available since v1.1.6)
protected string renderMenuItem(array $item)
$item array the menu item to be rendered. Please see items on what data might be in the item.
{return} string
Source Code: framework/zii/widgets/CMenu.php#243 (show)
protected function renderMenuItem($item)
{
    if(isset(
$item['url']))
    {
        
$label=$this->linkLabelWrapper===null $item['label'] : CHtml::tag($this->linkLabelWrapper$this->linkLabelWrapperHtmlOptions$item['label']);
        return 
CHtml::link($label,$item['url'],isset($item['linkOptions']) ? $item['linkOptions'] : array());
    }
    else
        return 
CHtml::tag('span',isset($item['linkOptions']) ? $item['linkOptions'] : array(), $item['label']);
}

Renders the content of a menu item. Note that the container and the sub-menus are not rendered here.

renderMenuRecursive() method
protected void renderMenuRecursive(array $items)
$items array the menu items to be rendered recursively
Source Code: framework/zii/widgets/CMenu.php#189 (show)
protected function renderMenuRecursive($items)
{
    
$count=0;
    
$n=count($items);
    foreach(
$items as $item)
    {
        
$count++;
        
$options=isset($item['itemOptions']) ? $item['itemOptions'] : array();
        
$class=array();
        if(
$item['active'] && $this->activeCssClass!='')
            
$class[]=$this->activeCssClass;
        if(
$count===&& $this->firstItemCssClass!==null)
            
$class[]=$this->firstItemCssClass;
        if(
$count===$n && $this->lastItemCssClass!==null)
            
$class[]=$this->lastItemCssClass;
        if(
$this->itemCssClass!==null)
            
$class[]=$this->itemCssClass;
        if(
$class!==array())
        {
            if(empty(
$options['class']))
                
$options['class']=implode(' ',$class);
            else
                
$options['class'].=' '.implode(' ',$class);
        }

        echo 
CHtml::openTag('li'$options);

        
$menu=$this->renderMenuItem($item);
        if(isset(
$this->itemTemplate) || isset($item['template']))
        {
            
$template=isset($item['template']) ? $item['template'] : $this->itemTemplate;
            echo 
strtr($template,array('{menu}'=>$menu));
        }
        else
            echo 
$menu;

        if(isset(
$item['items']) && count($item['items']))
        {
            echo 
"\n".CHtml::openTag('ul',isset($item['submenuOptions']) ? $item['submenuOptions'] : $this->submenuHtmlOptions)."\n";
            
$this->renderMenuRecursive($item['items']);
            echo 
CHtml::closeTag('ul')."\n";
        }

        echo 
CHtml::closeTag('li')."\n";
    }
}

Recursively renders the menu items.

run() method
public void run()
Source Code: framework/zii/widgets/CMenu.php#165 (show)
public function run()
{
    
$this->renderMenu($this->items);
}

Calls renderMenu to render the menu.

Total 4 comments

#14212 report it
__construct() at 2013/07/26 04:02pm
Deleting a record via menu, using CSRF

If you use CSRF on your site - you shoud modify the default menu code like this:

(...)
array(
    'label'=>'Delete model',
    'url'=>'#',
    'linkOptions'=>
        array(
            'submit'  => array('delete','id'=>$model->id),
            'confirm' => 'Delete?! Really?',
            'csrf' => true),
    ),
#8495 report it
marcovtwout at 2012/06/07 09:14am
Use CMenu to issue a post request

Using the linkOptions property of an item, we can make it do post requests!

(..)
array(
    'label' => 'Delete model',
    'url' => '#',
    'linkOptions' => array(
        'submit' => array('delete', 'id' => $model->id),
        'confirm' => 'Are you sure you want to delete this model?')
    ),
),
(..)

CHtml::link

#2470 report it
Steve Friedl at 2011/01/06 12:48pm
Styling applied to the LI element

When CMenu is applying styles (active, first, last, etc.), the classes are applied directly to the <LI> element and not to the links contained within.

#2351 report it
ianaré at 2010/12/16 05:25am
active items

Just to note that auto active items don't work properly unless the 'url' is in the form of an array. It must also be the complete route, so setting '/site' will not work, but 'site/index' will.

Leave a comment

Please to leave your comment.