Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered dropDownList using relations?

I have some forms in Yii using the following to get lists of data from related tables in the form of a drop down:

dropDownList(CHtml::listData(Company::model()->findAll(array('order' => 'company ASC'))));

This works, but that means for every drop down list (which theres a lot of) I'm putting this array('order' => 'company ASC' in every one.

Is this the best way to do it? Is there not a way to get this data using the model relations(), and specifying the order within the relation?

like image 522
djt Avatar asked Mar 07 '11 17:03

djt


1 Answers

I believe that the correct way to do this is by using scopes.

You can define any number of scopes that order the result set and use them like so:

Company::model()->scopeName()->findAll();

If your application always requires companies to be fetched in a sorted order, you can even define a default scope in your model class:

public function defaultScope() {
    return array('order' => 'company ASC');
}

This will result in every call to Company::model()->findAll(); returning sorted results.

like image 190
Jon Avatar answered Oct 17 '22 22:10

Jon