Using (or not using) CSort with DbCriteria

How to use CSort in Yii

We often turn to widgets and classes that are provided within a framework without really understanding the reasons why we might or might not use them.  In our training materials, you will always find the predicted way to use such widget in an ideal case.

But what we are often lacking is a "when to use this" and a "when NOT to use this" section at the top ...

So this brings me to CSort and when not to use it.  Or, unusually, in this case, when to use it.  In the search function of your model ... period!

That's it ??? Yep, that's it.  When else would you want to use it?

And even then, several times I have used it sparingly, even in the search function, perhaps like this:



if ($this->_randomSort) {
    $criteria->order='RAND()'
} else {
    $sort = new CSort();
    $sort->attributes = array(
                        'ref',
                        'title',
                        'sleeps',
                        'bedrooms',
                        'overview',
                        'min_price',
                        'max_price',
                        //....            
                    );
}

And there you have the answer, in a nutshell.  Elsewhere, if you want to sort, either use the order method of the DbCriteria object or by using the model()->findBySQL method, in both cases, specifying the SQL directly.



$post=Post::model()->findBySql($sql,$params);


Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...


Beginning Yii ...

I'm very excited about a new Yii Training course that has just been published.

The course is designed for anyone wanting to learn Yii, whether new to frameworks or converting from another.

Eight chapters, each having five videos of between 3 and 5 minutes, take you through the basics of the Yii Framework, building a web application step-by-step.

Save 40% - introductory offer $20.99 / £13.19 / €16.19 / A$20.99

Leave a Comment

twitterfacebookgooglelinkedin https://me.yahoo.com