add simple database menu in main.php, where 2 define a model

I have database menu that works in site/index.php and I want to have it as main menu so I transfered code to layouts/main.php but now yii get error: Invalid argument supplied for foreach() even when I access site/index page


<?php foreach ($Kategorijas as $Kategorija): ?>

<li> <?php echo CHtml::link($Kategorija->name, array('kategorije/?id='.$Kategorija->id,)); ?> </li>

<?php 	endforeach; ?>

I have in SiteController.php:


	public function actionIndex()

	{

		$Criteria = new CDbCriteria(); //kategorije menu

		$Criteria->select = "*";

		$Criteria->order = "id ASC";

		$this->render('index', array('Kategorijas' => Kategorija::model()->findAll($Criteria) ));

	}

How can I make this database menu works in my main.php?

create a widget

you could extend zii.widgets.CMenu, override init() and create your items there

Thanks mbi for fast reply. So I have


class MyWidget extends CWidget

{

    public function init()

    {

        // this method is called by CController::beginWidget()

    }

 

    public function run()

    {

        // this method is called by CController::endWidget()

    }

}

and I have 2 call my model and output foreach. I am stuck on this for houers, could You help me please on this simple example?

I did it:

I made in protected/components file Menu_kategorije.php:


<?php

class Menu_kategorije extends CWidget {

	

//	public $Kategorijas = array();

 

	public function run() {

		$Criteria = new CDbCriteria(); //kategorije menu

		$Criteria->select = "*";

		$Criteria->order = "id ASC";

		

		$this->render('menu_kategorije', array('Kategorijas' => Kategorija::model()->findAll($Criteria) ));

	}

    


}

?>

and made protected/components/view folder and added menu_kategorije.php:


          <!-- Block Top Menu module -->

          <div id="categories_block_top">

            <div class="block_content">

              <ul class="tree dhtml">

			<?php	foreach ($Kategorijas as $Kategorija): ?>

				<li>	<?php echo CHtml::link($Kategorija->name, array('kategorije/?id='.$Kategorija->id,)); ?> </li>

			<?php 	endforeach; ?>

                

              </ul>

            </div>

          </div>

file and in main.php:


<?php $this->widget('application.components.Menu_kategorije'); ?>