[SOLVED] listData sorting

Can anybody tell me how I can add sorting to the following code?

CHtml::activeDropDownList($model, 'idModel', CHtml::listData(MyModel::model()->findAll(), 'id', 'strName'));

I'd like to get listData ordered by the column 'strName'.






unfortunately this returns an error:

"Invalid argument supplied for foreach()"

sorry, asort() expects the first parameter to be variable because it is using reference.


sorry, asort() expects the first parameter to be variable because it is using reference.

which means?

no sorting for this function?

Why don't you sort on retrieval from your model. Your database probably is faster at sorting stuff than php is. Just set the 'order' parameter to 'strName ASC'

ok, but in which function should I do this (I'm a newbie in Yii :-P)?

You could write a method in MyModel and call this method in view to get the sorted list data.


CHtml::activeDropDownList($model, 'idModel', CHtml::listData(MyModel::model()->findAll(array('order'=>'strName ASC')), 'id', 'strName'));

If it doesn't work like this, look in the documentation in the database section.

Yeah, this is better by using DB sorting.

Yeah, works perfectly :slight_smile:

I agree in doing this on the database.

Perfect. Thanks a lot guys.

I would have never thought that is where the sort by clause would go. I misunderstood the findAll argument “condition” to just be the criteria of the SQL statement’s WHERE clause, and as a result, I thought there must be a different way to specify the order by clause.

Now I see from the api doc, the condition type can be mixed, either a string or an array.

So it also works as findAll(‘1=1 order by name’),

I did not understand the reason for the array, since it was being passed only one value, until I viewed the API section for CDbCriteria and the __construct() method, which shows that it expects an array as input, and does a foreach loop for each key value pair of the input array, and then assigns properties to the CDbCriteria object… it’s nice to have good documentation, thank you!

In my case the following DIDN’T work:

asort(CHtml::listData(Country::model()->findAll(array('order'=>'t.Name')), 'ID', 'Name'));

But the following DID work:

$data = CHtml::listData(Country::model()->findAll(array('order'=>'t.Name')), 'ID', 'Name');


Just wanted to mention it, in case you need to sort after results are returned.

For example: I have the ‘order’ clause in my SQL, but in some cases I manipulate the data in the ‘afterFind()’ method, so that the eventual list is not ordered correctly anymore.

PS: ‘afterFind()’ is the method executed when the onAfterFind() event of CActiveRecord is raised.

It’s no wonder… You’re posting in the Yii 1.0 forum. Try the 1.1 forum. :)