开发者

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 o开发者_StackOverflowf) 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?


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.


I usually add an opts() methods to each model that could be used as source for a dropdown:

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;
    }

It's used like this

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

If you need the same options several times on a page, you could even "cache" the result in a private static class variable or use DAO to fetch the list data in a more efficient way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜