# Sort

> Sort represents information relevant to sorting.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [data](/docs/api/yii/data/index.md) › Sort

| class | `yii\data\Sort` |
| --- | --- |
| Extends | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/data/Sort.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/data/Sort.php#L82) |

Sort represents information relevant to sorting.

When data needs to be sorted according to one or several attributes,
we can use Sort to represent the sorting information and generate
appropriate hyperlinks that can lead to sort actions.

A typical usage example is as follows,

```
public function actionIndex()
{
    $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',
            ],
        ],
    ]);

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

    return $this->render('index', [
         'models' => $models,
         'sort' => $sort,
    ]);
}
```

View:

```
// display links leading to sort actions
echo $sort->link('name') . ' | ' . $sort->link('age');

foreach ($models as $model) {
    // display $model here
}
```

In the above, we declare two [`$attributes`](/docs/api/yii/data/sort/index.md#property-attributes) that support sorting: `name` and `age`.
We pass the sort information to the Article query so that the query results are
sorted by the orders specified by the Sort object. In the view, we show two hyperlinks
that can lead to pages with the data sorted by the corresponding attributes.

For more details and usage information on Sort, see the [guide article on sorting](/docs/guide/output-sorting/index.md).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$attributeOrders`](#property-attributeOrders) | `array\|null` | Sort directions indexed by attribute names. | `Sort` |
| [`$attributes`](#property-attributes) | `array` | List of attributes that are allowed to be sorted. Default: `[]`. | `Sort` |
| [`$defaultOrder`](#property-defaultOrder) | `array\|null` | The order that should be used when the current request does not specify any order. Default: `null`. | `Sort` |
| [`$enableMultiSort`](#property-enableMultiSort) | `bool` | Whether the sorting can be applied to multiple attributes simultaneously. Default: `false`. | `Sort` |
| [`$modelClass`](#property-modelClass) | `string\|null` | The name of the [`Model`](/docs/api/yii/base/model/index.md)-based class used by the [`link()`](/docs/api/yii/data/sort/index.md#method-link) method to retrieve attributes' labels. Default: `null`. Available since 2.0.49. | `Sort` |
| [`$orders`](#property-orders) read-only | `array` | The columns (keys) and their corresponding sort directions (values). | `Sort` |
| [`$params`](#property-params) | `array\|null` | Parameters (name => value) that should be used to obtain the current sort directions and to create new sort URLs. Default: `null`. | `Sort` |
| [`$route`](#property-route) | `string\|null` | The route of the controller action for displaying the sorted contents. Default: `null`. | `Sort` |
| <span id="property-separator"></span>`$separator` | `string` | The character used to separate different attributes that need to be sorted by. Default: `','`. | `Sort` |
| <span id="property-sortFlags"></span>`$sortFlags` | `int` | Allow to control a value of the fourth parameter which will be passed to `ArrayHelper::multisort()` Default: `SORT_REGULAR`. Available since 2.0.33. | `Sort` |
| [`$sortParam`](#property-sortParam) | `string` | The name of the parameter that specifies which attributes to be sorted in which direction. Default: `'sort'`. | `Sort` |
| [`$urlManager`](#property-urlManager) | [`yii\web\UrlManager`](/docs/api/yii/web/urlmanager/index.md)`\|null` | The URL manager used for creating sort URLs. Default: `null`. | `Sort` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/baseobject/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/baseobject/index.md#method-__get) | Returns the value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/baseobject/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/baseobject/index.md#method-__set) | Sets value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/baseobject/index.md#method-__unset) | Sets an object property to null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`createSortParam()`](#method-createSortParam) | Creates the sort variable for the specified attribute. | `Sort` |
| [`createUrl()`](#method-createUrl) | Creates a URL for sorting the data by the specified attribute. | `Sort` |
| [`getAttributeOrder()`](#method-getAttributeOrder) | Returns the sort direction of the specified attribute in the current request. | `Sort` |
| [`getAttributeOrders()`](#method-getAttributeOrders) | Returns the currently requested sort information. | `Sort` |
| [`getOrders()`](#method-getOrders) | Returns the columns and their corresponding sort directions. | `Sort` |
| [`hasAttribute()`](#method-hasAttribute) | Returns a value indicating whether the sort definition supports sorting by the named attribute. | `Sort` |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/baseobject/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/baseobject/index.md#method-hasProperty) | Returns a value indicating whether a property is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`init()`](#method-init) | Normalizes the [`$attributes`](/docs/api/yii/data/sort/index.md#property-attributes) property. | `Sort` |
| [`link()`](#method-link) | Generates a hyperlink that links to the sort action to sort by the specified attribute. | `Sort` |
| [`setAttributeOrders()`](#method-setAttributeOrders) | Sets up the currently sort information. | `Sort` |
| [`parseSortParam()`](#method-parseSortParam) protected | Parses the value of [`$sortParam`](/docs/api/yii/data/sort/index.md#property-sortParam) into an array of sort attributes. | `Sort` |
| [`resolveRoute()`](#method-resolveRoute) protected | Resolves the target route from [`$route`](/docs/api/yii/data/sort/index.md#property-route), the active controller, or [`Application::$requestedRoute`](/docs/api/yii/base/application/index.md#property-requestedRoute). | `Sort` |

## Property details

### $attributeOrders <span id="property-attributeOrders"></span>

```php
public array|null $attributeOrders
```

Sort directions indexed by attribute names.

Sort direction can
be either `SORT_ASC` for ascending order or `SORT_DESC` for descending order.

### $attributes <span id="property-attributes"></span>

```php
public array $attributes = []
```

List of attributes that are allowed to be sorted.

Its syntax can be
described using the following example:

```
[
    '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',
    ],
]
```

In the above, two attributes are declared: `age` and `name`. The `age` attribute is
a simple attribute which is equivalent to the following:

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

Since 2.0.12 particular sort direction can be also specified as direct sort expression, like following:

```
'name' => [
    'asc' => '[[last_name]] ASC NULLS FIRST', // PostgreSQL specific feature
    'desc' => '[[last_name]] DESC NULLS LAST',
]
```

The `name` attribute is a composite attribute:

- The `name` key represents the attribute name which will appear in the URLs leading
  to sort actions.
- The `asc` and `desc` elements specify how to sort by the attribute in ascending
  and descending orders, respectively. Their values represent the actual columns and
  the directions by which the data should be sorted by.
- The `default` element specifies by which direction the attribute should be sorted
  if it is not currently sorted (the default value is ascending order).
- The `label` element specifies what label should be used when calling [`link()`](/docs/api/yii/data/sort/index.md#method-link) to create
  a sort link. If not set, [`Inflector::camel2words()`](/docs/api/yii/helpers/baseinflector/index.md#method-camel2words) will be called to get a label.
  Note that it will not be HTML-encoded.

Note that if the Sort object is already created, you can only use the full format
to configure every attribute. Each attribute must include these elements: `asc` and `desc`.

### $defaultOrder <span id="property-defaultOrder"></span>

```php
public array|null $defaultOrder = null
```

The order that should be used when the current request does not specify any order.

The array keys are attribute names and the array values are the corresponding sort directions. For example,

```
[
    'name' => SORT_ASC,
    'created_at' => SORT_DESC,
]
```

### $enableMultiSort <span id="property-enableMultiSort"></span>

```php
public bool $enableMultiSort = false
```

Whether the sorting can be applied to multiple attributes simultaneously.

Defaults to `false`, which means each time the data can only be sorted by one attribute.

### $modelClass <span id="property-modelClass"></span>

```php
public string|null $modelClass = null
```

The name of the [`Model`](/docs/api/yii/base/model/index.md)-based class used by the [`link()`](/docs/api/yii/data/sort/index.md#method-link) method to retrieve attributes' labels.

See [`link()`](/docs/api/yii/data/sort/index.md#method-link) method for details.

**Since**

2.0.49

### $orders <span id="property-orders"></span>

```php
public array $orders
```

The columns (keys) and their corresponding sort directions (values).

This can
be passed to [`Query::orderBy()`](/docs/api/yii/db/querytrait/index.md#method-orderBy) to construct a DB query.

**Access**

Read-only (virtual property).

### $params <span id="property-params"></span>

```php
public array|null $params = null
```

Parameters (name => value) that should be used to obtain the current sort directions and to create new sort URLs.

If not set, `$_GET` will be used instead.

In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.

The array element indexed by [`$sortParam`](/docs/api/yii/data/sort/index.md#property-sortParam) is considered to be the current sort directions.
If the element does not exist, the [default order](/docs/api/yii/data/sort/index.md#property-defaultOrder) will be used.

### $route <span id="property-route"></span>

```php
public string|null $route = null
```

The route of the controller action for displaying the sorted contents.

If not set, it means using the currently requested route.

### $sortParam <span id="property-sortParam"></span>

```php
public string $sortParam = 'sort'
```

The name of the parameter that specifies which attributes to be sorted in which direction.

Defaults to `sort`.

### $urlManager <span id="property-urlManager"></span>

```php
public yii\web\UrlManager|null $urlManager = null
```

The URL manager used for creating sort URLs.

If not set,
the `urlManager` application component will be used.

## Method details

### createSortParam() <span id="method-createSortParam"></span>

```php
public function createSortParam(string $attribute): string
```

Creates the sort variable for the specified attribute.

The newly created sort variable can be used to create a URL that will lead to
sorting by the specified attribute.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The attribute name |

**Returns**

`string`: The value of the sort variable

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the specified attribute is not defined in [`$attributes`](/docs/api/yii/data/sort/index.md#property-attributes)

### createUrl() <span id="method-createUrl"></span>

```php
public function createUrl(string $attribute, bool $absolute = false): string
```

Creates a URL for sorting the data by the specified attribute.

This method will consider the current sorting status given by [`$attributeOrders`](/docs/api/yii/data/sort/index.md#property-attributeOrders).
For example, if the current page already sorts the data by the specified attribute in ascending order,
then the URL created will lead to a page that sorts the data by the specified attribute in descending order.

The target route is determined by [`resolveRoute()`](/docs/api/yii/data/sort/index.md#method-resolveRoute) when [`$route`](/docs/api/yii/data/sort/index.md#property-route) is not configured.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The attribute name |
| `$absolute` | `bool` | Whether to create an absolute URL. Defaults to `false`. |

**Returns**

`string`: The URL for sorting. False if the attribute is invalid.

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the attribute is unknown, or if [`resolveRoute()`](/docs/api/yii/data/sort/index.md#method-resolveRoute) cannot determine a route.

**See also**

- [`$attributeOrders`](/docs/api/yii/data/sort/index.md#property-attributeOrders)
- [`$params`](/docs/api/yii/data/sort/index.md#property-params)

### getAttributeOrder() <span id="method-getAttributeOrder"></span>

```php
public function getAttributeOrder(string $attribute): int|null
```

Returns the sort direction of the specified attribute in the current request.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The attribute name |

**Returns**

`int|null`: Sort direction of the attribute. Can be either `SORT_ASC` for ascending order or `SORT_DESC` for descending order. Null is returned if the attribute is invalid or does not need to be sorted.

### getAttributeOrders() <span id="method-getAttributeOrders"></span>

```php
public function getAttributeOrders(bool $recalculate = false): array
```

Returns the currently requested sort information.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$recalculate` | `bool` | Whether to recalculate the sort directions |

**Returns**

`array`: Sort directions indexed by attribute names. Sort direction can be either `SORT_ASC` for ascending order or `SORT_DESC` for descending order.

### getOrders() <span id="method-getOrders"></span>

```php
public function getOrders(bool $recalculate = false): array
```

Returns the columns and their corresponding sort directions.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$recalculate` | `bool` | Whether to recalculate the sort directions |

**Returns**

`array`: The columns (keys) and their corresponding sort directions (values). This can be passed to [`Query::orderBy()`](/docs/api/yii/db/querytrait/index.md#method-orderBy) to construct a DB query.

### hasAttribute() <span id="method-hasAttribute"></span>

```php
public function hasAttribute(string $name): bool
```

Returns a value indicating whether the sort definition supports sorting by the named attribute.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |

**Returns**

`bool`: Whether the sort definition supports sorting by the named attribute.

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Normalizes the [`$attributes`](/docs/api/yii/data/sort/index.md#property-attributes) property.

**Returns**

`mixed`

### link() <span id="method-link"></span>

```php
public function link(string $attribute, array $options = []): string
```

Generates a hyperlink that links to the sort action to sort by the specified attribute.

Based on the sort direction, the CSS class of the generated hyperlink will be appended
with "asc" or "desc".

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The attribute name by which the data should be sorted by. |
| `$options` | `array` | Additional HTML attributes for the hyperlink tag. There is one special attribute `label` which will be used as the label of the hyperlink. If this is not set, the label defined in [`$attributes`](/docs/api/yii/data/sort/index.md#property-attributes) will be used. If no label is defined, it will be retrieved from the instance of [`$modelClass`](/docs/api/yii/data/sort/index.md#property-modelClass) (if [`$modelClass`](/docs/api/yii/data/sort/index.md#property-modelClass) is not null) or generated from attribute name using [`Inflector::camel2words()`](/docs/api/yii/helpers/baseinflector/index.md#method-camel2words). Note that it will not be HTML-encoded. |

**Returns**

`string`: The generated hyperlink

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the attribute is unknown

### setAttributeOrders() <span id="method-setAttributeOrders"></span>

```php
public function setAttributeOrders(array|null $attributeOrders, bool $validate = true): mixed
```

Sets up the currently sort information.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributeOrders` | `array\|null` | Sort directions indexed by attribute names. Sort direction can be either `SORT_ASC` for ascending order or `SORT_DESC` for descending order. |
| `$validate` | `bool` | Whether to validate given attribute orders against [`$attributes`](/docs/api/yii/data/sort/index.md#property-attributes) and [`$enableMultiSort`](/docs/api/yii/data/sort/index.md#property-enableMultiSort). If validation is enabled incorrect entries will be removed. |

**Returns**

`mixed`

**Since**

2.0.10

### parseSortParam() <span id="method-parseSortParam"></span>

```php
protected function parseSortParam(mixed $param): array
```

Parses the value of [`$sortParam`](/docs/api/yii/data/sort/index.md#property-sortParam) into an array of sort attributes.

The format must be the attribute name only for ascending
or the attribute name prefixed with `-` for descending.

For example the following return value will result in ascending sort by
`category` and descending sort by `created_at`:

```
[
    'category',
    '-created_at'
]
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$param` | `mixed` | The value of the [`$sortParam`](/docs/api/yii/data/sort/index.md#property-sortParam). |

**Returns**

`array`: The valid sort attributes.

**Since**

2.0.12

**See also**

- [`$separator`](/docs/api/yii/data/sort/index.md#property-separator) (for the attribute name separator.)
- [`$sortParam`](/docs/api/yii/data/sort/index.md#property-sortParam)

### resolveRoute() <span id="method-resolveRoute"></span>

```php
protected function resolveRoute(): string
```

Resolves the target route from [`$route`](/docs/api/yii/data/sort/index.md#property-route), the active controller, or [`Application::$requestedRoute`](/docs/api/yii/base/application/index.md#property-requestedRoute).

The `requestedRoute` fallback supports standalone actions where no controller is hosting the request.

**Returns**

`string`: The resolved route.

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if no route can be resolved.