Sort
extends BaseObject
in package
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.
Tags
Table of Contents
Properties
- $attributeOrders : array<string|int, mixed>
- $attributes : array<string|int, mixed>
- $defaultOrder : array<string|int, mixed>|null
- $enableMultiSort : bool
- $modelClass : string|null
- $orders : array<string|int, mixed>
- $params : array<string|int, mixed>|null
- $route : string|null
- $separator : string
- $sortFlags : int
- $sortParam : string
- $urlManager : UrlManager|null
- $_attributeOrders : array<string|int, mixed>
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of an object property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets value of an object property.
- __unset() : mixed
- Sets an object property to null.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- createSortParam() : string
- Creates the sort variable for the specified attribute.
- createUrl() : string
- Creates a URL for sorting the data by the specified attribute.
- getAttributeOrder() : int|null
- Returns the sort direction of the specified attribute in the current request.
- getAttributeOrders() : array<string|int, mixed>
- Returns the currently requested sort information.
- getOrders() : array<string|int, mixed>
- Returns the columns and their corresponding sort directions.
- hasAttribute() : bool
- Returns a value indicating whether the sort definition supports sorting by the named attribute.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined.
- init() : mixed
- Normalizes the [[attributes]] property.
- link() : string
- Generates a hyperlink that links to the sort action to sort by the specified attribute.
- setAttributeOrders() : mixed
- Sets up the currently sort information.
- parseSortParam() : array<string|int, mixed>
- Parses the value of [[sortParam]] into an array of sort attributes.
Properties
$attributeOrders
public
array<string|int, mixed>
$attributeOrders
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.
$attributes
public
array<string|int, mixed>
$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
anddesc
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, [[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
.
$defaultOrder
public
array<string|int, mixed>|null
$defaultOrder
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,
]
Tags
$enableMultiSort
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
public
string|null
$modelClass
the name of the [[\yii\base\Model]]-based class used by the [[link()]] method to retrieve attributes' labels. See [[link]] method for details.
Tags
$orders read-only
public
array<string|int, mixed>
$orders
The columns (keys) and their corresponding sort directions (values). This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
$params
public
array<string|int, mixed>|null
$params
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 [[defaultOrder|default order]] will be used.
Tags
$route
public
string|null
$route
the route of the controller action for displaying the sorted contents. If not set, it means using the currently requested route.
$separator
public
string
$separator
= ','
the character used to separate different attributes that need to be sorted by.
$sortFlags
public
int
$sortFlags
= SORT_REGULAR
Allow to control a value of the fourth parameter which will be passed to [[ArrayHelper::multisort()]]
Tags
$sortParam
public
string
$sortParam
= 'sort'
the name of the parameter that specifies which attributes to be sorted
in which direction. Defaults to sort
.
Tags
$urlManager
public
UrlManager|null
$urlManager
the URL manager used for creating sort URLs. If not set,
the urlManager
application component will be used.
$_attributeOrders
private
array<string|int, mixed>
$_attributeOrders
the currently requested sort order as computed by [[getAttributeOrders]].
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
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.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
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.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Returns the value of an object property.
public
__get(string $name) : mixed
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $object->property;
.
Parameters
- $name : string
-
the property name
Tags
Return values
mixed —the property value
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
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.
Parameters
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set (not null).
__set()
Sets value of an object property.
public
__set(string $name, mixed $value) : mixed
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $object->property = $value;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__unset()
Sets an object property to null.
public
__unset(string $name) : mixed
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.
Parameters
- $name : string
-
the property name
Tags
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ]) : bool
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);
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ]) : bool
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);
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
createSortParam()
Creates the sort variable for the specified attribute.
public
createSortParam(string $attribute) : string
The newly created sort variable can be used to create a URL that will lead to sorting by the specified attribute.
Parameters
- $attribute : string
-
the attribute name
Tags
Return values
string —the value of the sort variable
createUrl()
Creates a URL for sorting the data by the specified attribute.
public
createUrl(string $attribute[, bool $absolute = false ]) : string
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.
Parameters
- $attribute : string
-
the attribute name
- $absolute : bool = false
-
whether to create an absolute URL. Defaults to
false
.
Tags
Return values
string —the URL for sorting. False if the attribute is invalid.
getAttributeOrder()
Returns the sort direction of the specified attribute in the current request.
public
getAttributeOrder(string $attribute) : int|null
Parameters
- $attribute : string
-
the attribute name
Return values
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()
Returns the currently requested sort information.
public
getAttributeOrders([bool $recalculate = false ]) : array<string|int, mixed>
Parameters
- $recalculate : bool = false
-
whether to recalculate the sort directions
Return values
array<string|int, mixed> —sort directions indexed by attribute names.
Sort direction can be either SORT_ASC
for ascending order or
SORT_DESC
for descending order.
getOrders()
Returns the columns and their corresponding sort directions.
public
getOrders([bool $recalculate = false ]) : array<string|int, mixed>
Parameters
- $recalculate : bool = false
-
whether to recalculate the sort directions
Return values
array<string|int, mixed> —the columns (keys) and their corresponding sort directions (values). This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
hasAttribute()
Returns a value indicating whether the sort definition supports sorting by the named attribute.
public
hasAttribute(string $name) : bool
Parameters
- $name : string
-
the attribute name
Return values
bool —whether the sort definition supports sorting by the named attribute.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name) : bool
The default implementation is a call to php function method_exists()
.
You may override this method when you implemented the php magic method __call()
.
Parameters
- $name : string
-
the method name
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined.
public
hasProperty(string $name[, bool $checkVars = true ]) : bool
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);
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
Tags
Return values
bool —whether the property is defined
init()
Normalizes the [[attributes]] property.
public
init() : mixed
link()
Generates a hyperlink that links to the sort action to sort by the specified attribute.
public
link(string $attribute[, array<string|int, mixed> $options = [] ]) : string
Based on the sort direction, the CSS class of the generated hyperlink will be appended with "asc" or "desc".
Parameters
- $attribute : string
-
the attribute name by which the data should be sorted by.
- $options : array<string|int, mixed> = []
-
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, it will be retrieved from the instance of [[modelClass]] (if [[modelClass]] is not null) or generated from attribute name using [[\yii\helpers\Inflector::camel2words()]]. Note that it will not be HTML-encoded.
Tags
Return values
string —the generated hyperlink
setAttributeOrders()
Sets up the currently sort information.
public
setAttributeOrders(array<string|int, mixed>|null $attributeOrders[, bool $validate = true ]) : mixed
Parameters
- $attributeOrders : array<string|int, mixed>|null
-
sort directions indexed by attribute names. Sort direction can be either
SORT_ASC
for ascending order orSORT_DESC
for descending order. - $validate : bool = true
-
whether to validate given attribute orders against [[attributes]] and [[enableMultiSort]]. If validation is enabled incorrect entries will be removed.
Tags
parseSortParam()
Parses the value of [[sortParam]] into an array of sort attributes.
protected
parseSortParam(string $param) : array<string|int, mixed>
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
- $param : string
-
the value of the [[sortParam]].
Tags
Return values
array<string|int, mixed> —the valid sort attributes.