我有一个由 Yii2 GridView 渲染的表格。表头包含按日期排序的链接。如果我单击它,它首先按升序对表格进行排序,第二次单击时按降序对表格进行排序。但我想在第一次点击时降序排列。
我通过搜索控制器的搜索方法(asc->SORT_DESC)中的一个 hack 解决了这个问题:
$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,
],
],
]);
您可以使用
sort
中的$dataProvider
选项。它将在 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']];