A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.yiiframework.com/doc/guide/2.0/en/output-sorting below:

Displaying Data: Sorting | The Definitive Guide to Yii 2.0

Sorting ΒΆ

When displaying multiple rows of data, it is often needed that the data be sorted according to some columns specified by end users. Yii uses a yii\data\Sort object to represent the information about a sorting schema. In particular,

To use yii\data\Sort, first declare which attributes can be sorted. Then retrieve the currently requested ordering information from attributeOrders or orders and use them to customize the data query. For example,

use yii\data\Sort;

$sort = new Sort([
    'attributes' => [
        'age',
        'name' => [
            'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
            'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
            'default' => SORT_DESC,
            'label' => 'Name',
        ],
    ],
]);

$articles = Article::find()
    ->where(['status' => 1])
    ->orderBy($sort->orders)
    ->all();

In the above example, two attributes are declared for the Sort object: age and name.

The age attribute is a simple attribute corresponding to the age attribute of the Article Active Record class. It is equivalent to the following declaration:

'age' => [
    'asc' => ['age' => SORT_ASC],
    'desc' => ['age' => SORT_DESC],
    'default' => SORT_ASC,
    'label' => Inflector::camel2words('age'),
]

The name attribute is a composite attribute defined by first_name and last_name of Article. It is declared using the following array structure:

Info: You can directly feed the value of orders to the database query to build its ORDER BY clause. Do not use attributeOrders because some attributes may be composite and cannot be recognized by the database query.

You can call yii\data\Sort::link() to generate a hyperlink upon which end users can click to request sorting the data by the specified attribute. You may also call yii\data\Sort::createUrl() to create a sortable URL. For example,



$sort->route = 'article/index';


echo $sort->link('name') . ' | ' . $sort->link('age');


echo $sort->createUrl('age');

yii\data\Sort checks the sort query parameter to determine which attributes are being requested for sorting. You may specify a default ordering via yii\data\Sort::$defaultOrder when the query parameter is not present. You may also customize the name of the query parameter by configuring the sortParam property.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4