首先按降序排序Yii2 Gridview

时间:2016-06-02 09:53:00

标签: sorting gridview yii2

我有一个由Yii2 GridView呈现的表。表头包含按日期排序的链接。如果我点击它,它会按升序对表格进行排序,然后按降序对第二次单击进行排序。但我想在第一次点击时降序。

我在搜索控制器的搜索方法中解决了这个问题(asc-> SORT_DESC):

   $dataProvider->sort->attributes['updated_at'] = [ 
      'asc'  => [$this->tablename() . '.updated_at' => SORT_DESC ], 
      'desc' => [$this->tablename() . '.updated_at' => SORT_ASC], 
   ]; 

有更好的解决方案吗?

4 个答案:

答案 0 :(得分:4)

使用default

  

"默认" element指定属性在当前未排序时应按哪个方向排序(默认值为升序)。

$dataProvider->sort->attributes['updated_at'] = [ 
    'default' => SORT_DESC
]; 

答案 1 :(得分:0)

$dataProvider = new ActiveDataProvider([
  'query' => YourClass::find(),
  'sort' => [
    'defaultOrder' => [
        'updated_at' => SORT_ASC,
    ],
  ],
]);

您可以在sort中使用$dataProvider选项。它会在ascending order中显示数据,当您第一次点击列时,它将首先显示在descending order中。

我检查了一下。它对我有用。

如需了解更多信息,请查看Rendering Data In List View & Grid View : Yii2

答案 2 :(得分:0)

我的解决方案:

  

添加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);

答案 3 :(得分:0)

$dataProvider->sort = ['defaultOrder' => ['id' => 'DESC']];