CMenu with dynamic subitems

Hi there!

I try to build a CMenu menu with dynamic subitems for one of the static 1st-level links:

- Link 1

- Link 2

- Link 3 (with Subs)

   - Sublink 1

   - Sublink 2

   - Sublink 3

   - [...]

- Link 4

My 1st-level links are static, but the sublinks come from a database and should therefore be dynamic in number.

Is this somehow possible with CMenu (or CDropDownMenu)?

Any ideas on that? :)



Look for my function (shorten version for this post):

function buildMainMenu()


    	$common_menu_items = array


            	array('label'=>'Main', 'url'=>array('/main/index')),


    	$menu = $common_menu_items;

    	if(app()->getModule('admin') !== null)



            	$adm = AdminModule::buildAdminMenu();

            	$admin_menu_item = array(array('label'=>'Admin', 'items'=>$adm));

            	$menu = array_merge($menu, $admin_menu_item);


    	return $menu;


It generates static top-level menu items Main and Admin and adds dynamically generated (buildAdminMenu function) contents as items (sub-menu) of Admin menu item. Inside this function you can do, whatever you want. I build menu basing on some configuration arrays, you can build it using DB (assuming you have or know how to write function that retrieves menu items from DB and converts it to array representation, which can be then used in CMenu). There was also an article about menu generated upon database. Look into Wiki (Cookbook).

Maybe this will help you.

Thanks for your input, I got it working :)

In case someone is interested on how to dynamically generate the CMenu items array:

Model: (retrieve categories from database)


	$sql = "[...]";

	$connection = Yii::app()->db;

	$command = $connection->createCommand($sql);

	$dataReader = $command->query();

	foreach ($dataReader as $row) {

	   $categories[] = array('label' => $row['category_id'], 'url' => array('downloads/category/cat/'.$row['category_id']));



View: (display the menu with subitems)

<?php $this->widget('zii.widgets.CMenu', array(

	'items' => array(

		array('label' => 'Home', 'url' => array('/site/index')),

		array('label' => 'Downloads', 'url' => array('/downloads'), 'items' =>



		array('label' => 'Upload', 'url' => array('/upload')),


)); ?>


Check if there are any $categories at all.

One thing, though: where would I ideally put the code for building the $categories and how would I include it?

thank you. I got it working too!

Im not able to make this work…<br />

I’m new to yii…<br />

So can you please explain how can I make this work…<br />

which part to put were.<br />

for now m getting the error…<br />

undefined $categories<br />

So please help