[英]Sorting Yii2 Gridview in descending order first
我有一個由Yii2 GridView呈現的表。 表頭包含按日期排序的鏈接。 如果我點擊它,它會按升序對表格進行排序,然后按降序對第二次單擊進行排序。 但我想在第一次點擊時降序。
我在搜索控制器的搜索方法中解決了它(asc-> SORT_DESC):
$dataProvider->sort->attributes['updated_at'] = [
'asc' => [$this->tablename() . '.updated_at' => SORT_DESC ],
'desc' => [$this->tablename() . '.updated_at' => SORT_ASC],
];
有更好的解決方案嗎?
使用default
:
“default”元素指定屬性在當前未排序時應按哪個方向排序(默認值為升序)。
$dataProvider->sort->attributes['updated_at'] = [
'default' => SORT_DESC
];
$dataProvider = new ActiveDataProvider([
'query' => YourClass::find(),
'sort' => [
'defaultOrder' => [
'updated_at' => SORT_ASC,
],
],
]);
您可以在$dataProvider
使用sort
選項。 它將ascending order
顯示數據,當您第一次單擊列時,它將首先descending order
顯示。
我檢查了一下。 它對我有用。
有關詳細信息,請查看列表視圖和網格視圖中的渲染數據:Yii2
我的解決方案
添加Sort.php
namespace backend\components;
use yii\base\InvalidConfigException;
class Sort extends \yii\data\Sort
{
/**
* @var int
*/
public $defaultSort = SORT_DESC;
/**
* Rewrite
* @param string $attribute the attribute name
* @return string the value of the sort variable
* @throws 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])) {
$direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
unset($directions[$attribute]);
} else {
$direction = isset($definition['default']) ? $definition['default'] : $this->defaultSort;
}
if ($this->enableMultiSort) {
$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);
}
}
在控制器中:
$dataProvider = new ActiveDataProvider([
'query' => MyModel::find(),
]);
/**@var $sort \backend\components\Sort */
$sort = Yii::createObject(array_merge(['class' => Sort::className()], [
'defaultOrder' => [
'_id' => SORT_ASC,
],
]));
$dataProvider->setSort($sort);
$dataProvider->sort = ['defaultOrder' => ['id' => 'DESC']];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.