Class yii\data\Sort

Inheritanceyii\data\Sort » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/data/Sort.php

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 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.

Public Properties

Hide inherited properties

Property Type Description Defined By
$attributeOrders array Sort directions indexed by attribute names. yii\data\Sort
$attributes array List of attributes that are allowed to be sorted. yii\data\Sort
$defaultOrder array The order that should be used when the current request does not specify any order. yii\data\Sort
$enableMultiSort boolean Whether the sorting can be applied to multiple attributes simultaneously. yii\data\Sort
$orders array The columns (keys) and their corresponding sort directions (values). yii\data\Sort
$params array|null Parameters (name => value) that should be used to obtain the current sort directions and to create new sort URLs. yii\data\Sort
$route string|null The route of the controller action for displaying the sorted contents. yii\data\Sort
$separator string The character used to separate different attributes that need to be sorted by. yii\data\Sort
$sortFlags integer Allow to control a value of the fourth parameter which will be passed to ArrayHelper::multisort() yii\data\Sort
$sortParam string The name of the parameter that specifies which attributes to be sorted in which direction. yii\data\Sort
$urlManager yii\web\UrlManager|null The URL manager used for creating sort URLs. yii\data\Sort

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
createSortParam() Creates the sort variable for the specified attribute. yii\data\Sort
createUrl() Creates a URL for sorting the data by the specified attribute. yii\data\Sort
getAttributeOrder() Returns the sort direction of the specified attribute in the current request. yii\data\Sort
getAttributeOrders() Returns the currently requested sort information. yii\data\Sort
getOrders() Returns the columns and their corresponding sort directions. yii\data\Sort
hasAttribute() Returns a value indicating whether the sort definition supports sorting by the named attribute. yii\data\Sort
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Normalizes the $attributes property. yii\data\Sort
link() Generates a hyperlink that links to the sort action to sort by the specified attribute. yii\data\Sort
setAttributeOrders() Sets up the currently sort information. yii\data\Sort

Protected Methods

Hide inherited methods

Method Description Defined By
parseSortParam() Parses the value of $sortParam into an array of sort attributes. yii\data\Sort

Property Details

Hide inherited properties

$attributeOrders public property

Sort directions indexed by attribute names. Sort direction can be either SORT_ASC for ascending order or SORT_DESC for descending order. Note that the type of this property differs in getter and setter. See getAttributeOrders() and setAttributeOrders() for details.

public array $attributeOrders null
$attributes public property

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() to create a sort link. If not set, yii\helpers\Inflector::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.

public array $attributes = []
$defaultOrder public property

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,
]

See also $attributeOrders.

public array $defaultOrder null
$enableMultiSort public property

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.

public boolean $enableMultiSort false
$orders public property

The columns (keys) and their corresponding sort directions (values). This can be passed to yii\db\Query::orderBy() to construct a DB query.

public array $orders null
$params public property

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 is considered to be the current sort directions. If the element does not exist, the default order will be used.

See also:

public array|null $params null
$route public property

The route of the controller action for displaying the sorted contents. If not set, it means using the currently requested route.

public string|null $route null
$separator public property

The character used to separate different attributes that need to be sorted by.

public string $separator ','
$sortFlags public property (available since version 2.0.33)

Allow to control a value of the fourth parameter which will be passed to ArrayHelper::multisort()

public integer $sortFlags SORT_REGULAR
$sortParam public property

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

See also $params.

public string $sortParam 'sort'
$urlManager public property

The URL manager used for creating sort URLs. If not set, the urlManager application component will be used.

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\BaseObject::__call()

Calls the named method which is not a class method.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\BaseObject::__get()

Returns the value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $object->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\BaseObject::__isset()

Checks if a property is set, i.e. defined and not null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($object->property).

Note that if the property is not defined, false will be returned.

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set (not null).

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

Defined in: yii\base\BaseObject::__set()

Sets value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $object->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

Defined in: yii\base\BaseObject::__unset()

Sets an object property to null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($object->property).

Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
canGetProperty() public method

Defined in: yii\base\BaseObject::canGetProperty()

Returns a value indicating whether a property can be read.

A property is readable if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

Defined in: yii\base\BaseObject::canSetProperty()

Returns a value indicating whether a property can be set.

A property is writable if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
createSortParam() public method

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.

public string createSortParam ( $attribute )
$attribute string

The attribute name

return string

The value of the sort variable

throws yii\base\InvalidConfigException

if the specified attribute is not defined in $attributes

                public function createSortParam($attribute)
{
    if (!isset($this->attributes[$attribute])) {
        throw new InvalidConfigException("Unknown attribute: $attribute");
    }
    $definition = $this->attributes[$attribute];
    $directions = $this->getAttributeOrders();
    if (isset($directions[$attribute])) {
        if ($this->enableMultiSort) {
            if ($directions[$attribute] === SORT_ASC) {
                $direction = SORT_DESC;
            } else {
                $direction = null;
            }
        } else {
            $direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
        }
        unset($directions[$attribute]);
    } else {
        $direction = isset($definition['default']) ? $definition['default'] : SORT_ASC;
    }
    if ($this->enableMultiSort) {
        if ($direction !== null) {
            $directions = array_merge([$attribute => $direction], $directions);
        }
    } else {
        $directions = [$attribute => $direction];
    }
    $sorts = [];
    foreach ($directions as $attribute => $direction) {
        $sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
    }
    return implode($this->separator, $sorts);
}

            
createUrl() public method

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

This method will consider the current sorting status given by $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.

See also:

public string createUrl ( $attribute, $absolute false )
$attribute string

The attribute name

$absolute boolean

Whether to create an absolute URL. Defaults to false.

return string

The URL for sorting. False if the attribute is invalid.

throws yii\base\InvalidConfigException

if the attribute is unknown

                public function createUrl($attribute, $absolute = false)
{
    if (($params = $this->params) === null) {
        $request = Yii::$app->getRequest();
        $params = $request instanceof Request ? $request->getQueryParams() : [];
    }
    $params[$this->sortParam] = $this->createSortParam($attribute);
    $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
    $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
    if ($absolute) {
        return $urlManager->createAbsoluteUrl($params);
    }
    return $urlManager->createUrl($params);
}

            
getAttributeOrder() public method

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

public integer|null getAttributeOrder ( $attribute )
$attribute string

The attribute name

return integer|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.

                public function getAttributeOrder($attribute)
{
    $orders = $this->getAttributeOrders();
    return isset($orders[$attribute]) ? $orders[$attribute] : null;
}

            
getAttributeOrders() public method

Returns the currently requested sort information.

public array getAttributeOrders ( $recalculate false )
$recalculate boolean

Whether to recalculate the sort directions

return array

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

                public function getAttributeOrders($recalculate = false)
{
    if ($this->_attributeOrders === null || $recalculate) {
        $this->_attributeOrders = [];
        if (($params = $this->params) === null) {
            $request = Yii::$app->getRequest();
            $params = $request instanceof Request ? $request->getQueryParams() : [];
        }
        if (isset($params[$this->sortParam])) {
            foreach ($this->parseSortParam($params[$this->sortParam]) as $attribute) {
                $descending = false;
                if (strncmp($attribute, '-', 1) === 0) {
                    $descending = true;
                    $attribute = substr($attribute, 1);
                }
                if (isset($this->attributes[$attribute])) {
                    $this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
                    if (!$this->enableMultiSort) {
                        return $this->_attributeOrders;
                    }
                }
            }
        }
        if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
            $this->_attributeOrders = $this->defaultOrder;
        }
    }
    return $this->_attributeOrders;
}

            
getOrders() public method

Returns the columns and their corresponding sort directions.

public array getOrders ( $recalculate false )
$recalculate boolean

Whether to recalculate the sort directions

return array

The columns (keys) and their corresponding sort directions (values). This can be passed to yii\db\Query::orderBy() to construct a DB query.

                public function getOrders($recalculate = false)
{
    $attributeOrders = $this->getAttributeOrders($recalculate);
    $orders = [];
    foreach ($attributeOrders as $attribute => $direction) {
        $definition = $this->attributes[$attribute];
        $columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
        if (is_array($columns) || $columns instanceof \Traversable) {
            foreach ($columns as $name => $dir) {
                $orders[$name] = $dir;
            }
        } else {
            $orders[] = $columns;
        }
    }
    return $orders;
}

            
hasAttribute() public method

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

public boolean hasAttribute ( $name )
$name string

The attribute name

return boolean

Whether the sort definition supports sorting by the named attribute.

                public function hasAttribute($name)
{
    return isset($this->attributes[$name]);
}

            
hasMethod() public method

Defined in: yii\base\BaseObject::hasMethod()

Returns a value indicating whether a method is defined.

The default implementation is a call to php function method_exists(). You may override this method when you implemented the php magic method __call().

public boolean hasMethod ( $name )
$name string

The method name

return boolean

Whether the method is defined

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

Defined in: yii\base\BaseObject::hasProperty()

Returns a value indicating whether a property is defined.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also:

public boolean hasProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() public method

Normalizes the $attributes property.

public void init ( )

                public function init()
{
    $attributes = [];
    foreach ($this->attributes as $name => $attribute) {
        if (!is_array($attribute)) {
            $attributes[$attribute] = [
                'asc' => [$attribute => SORT_ASC],
                'desc' => [$attribute => SORT_DESC],
            ];
        } elseif (!isset($attribute['asc'], $attribute['desc'])) {
            $attributes[$name] = array_merge([
                'asc' => [$name => SORT_ASC],
                'desc' => [$name => SORT_DESC],
            ], $attribute);
        } else {
            $attributes[$name] = $attribute;
        }
    }
    $this->attributes = $attributes;
}

            
link() public method

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".

public string link ( $attribute, $options = [] )
$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 will be used. If no label is defined, yii\helpers\Inflector::camel2words() will be called to get a label. Note that it will not be HTML-encoded.

return string

The generated hyperlink

throws yii\base\InvalidConfigException

if the attribute is unknown

parseSortParam() protected method (available since version 2.0.12)

Parses the value of $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'
]

See also:

protected array parseSortParam ( $param )
$param string

The value of the $sortParam.

return array

The valid sort attributes.

                protected function parseSortParam($param)
{
    return is_scalar($param) ? explode($this->separator, $param) : [];
}

            
setAttributeOrders() public method (available since version 2.0.10)

Sets up the currently sort information.

public void setAttributeOrders ( $attributeOrders, $validate true )
$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 boolean

Whether to validate given attribute orders against $attributes and $enableMultiSort. If validation is enabled incorrect entries will be removed.

                public function setAttributeOrders($attributeOrders, $validate = true)
{
    if ($attributeOrders === null || !$validate) {
        $this->_attributeOrders = $attributeOrders;
    } else {
        $this->_attributeOrders = [];
        foreach ($attributeOrders as $attribute => $order) {
            if (isset($this->attributes[$attribute])) {
                $this->_attributeOrders[$attribute] = $order;
                if (!$this->enableMultiSort) {
                    break;
                }
            }
        }
    }
}