Ordered a dropDownList using relationships?

I have some forms in Yii, using the following to retrieve lists of data from linked tables as a drop-down list:

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

This works, but that means that for every drop-down list (which is a lot) I put this array('order' => 'company ASC'on each.

Is this the best way to do this? Is it impossible to obtain this data using model relations () and indicate the order in relation?

+5
source share
2 answers

I believe that the right way to do this is with scopes .

You can define any number of areas that organize the result set and use them like this:

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

, , :

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

, Company::model()->findAll(); .

+5

opts() , :

class Company extends CActiveRecord
{
    // ...

    public static opts()
    {
        $opts = array();
        foreach(self::model()->findAll(array('order'=>'name ASC')) as $model)
            $opts[$model->id] = $model->name;
        return $opts;
    }

echo $form->dropDownList($user, 'company_id', Company::opts());

, "" DAO .

+1

All Articles