Why Do We Write Queries In View

Hi in most examples on yii we write the query code for dropdowns in views. Isn’t it against MVC. if so then why do we do it.

I think it is demonstrated that way because it is easier to follow the example when you aren’t using the controller to run model methods and then pass data to the view.

I confess to using queries in views also but generally only for simple dropdown selects and things.

Could you give me an example showing this approach? I don’t remember any tutorial using queries in views. However, I almost always create custom methods like this in my models that are then used in my views in order to keep things clean

public function getFancyDropdownOptions()


    return CHtml::listData(MyModel::model()->findAll(),'id','name');


It can be done, but with moderation.

Like Haensel, I generally create a static method in the relevant model to return options for drop down lists, following much the same naming convention. A simple example might be:

    public static function getCompanyOptions()


        return CHtml::listData(self::model()->findAll(), 'Id', 'Name');


i too do the same. call a dropdown method. But why static. what are the advantages

Because then I can get the valid options without needing to create an instance of the class. For instance, if I was generating a drop down list to attach a User to a Company, I don’t have an existing instance of Company, so a static method is more appropriate.

Also, it makes more sense that the class itself generates a list of all companies rather than a specific Company instance; the individual instance doesn’t need to know about all of the other companies, it only cares about its own attributes.

It’s down to personal preference I suppose, but I find the static method to be more appropriate from a code perspective.

B) cool that’s a good suggestion. But i currently use it as Product::model()->dropdown() and i don’t create a instance of it. Is it the same

The model() method does return a default instance, but again, I feel that the method belongs with the class rather than the object. Both ways will work, so choose whichever suits you. :)