Access model in layout file

For example:

$products=Product::model()->findAll();

I want to access this object in my layouts/main.php file. Where do I put the code (which controller/action)?

It’s OK I got my answer! I just put

<?php foreach(Product::model()->findAll() as $data) { ?>

in the layout file!

But is there another way of doing this? For example if I wanted to specify criteria for the query? It would probably be easier if the query was generated in a controller.

If you want to access any models in your layout file, then you probably need to create a widget:




class WProducts extends CWidget

{

    public function run()

    {

        $models = Product::model()->findAll();

        $this->render('path.to.widget.view', array('models'=>$models));

    }

}



And put it into your layout:




<?php $this->widget('path.to.WProducts'); ?>



Now, it is an independent element of the interface (I guess it is supposed to be so).

Of course, you can face the situation, when some element should be action-dependent (like CBreadcrumbs). But as you can see, CBreadcrumbs is a widget too. It can take parameters, which allows to configure it depend on the current action.

So my answer is: use widgets :)

Or you could take a look at how the column2.php file uses the controller menu items and model a solution on that.

i do agree with the solution provided by andy_s :)

Another solution is Creating a Method in your model class and call this Method on view file and iterate through the result. :)

Since running a mysql queries on a view files are not a good approach of MVC practice. That is why you must go with the solution suggested by andy_s or you should do it as i have suggested :)

But Running direct model Queries on view file is not a good one.