Yii: Reverse CGridView display order

2019-07-30 20:30发布

How can I reverse the order of CGridView (showing newest on top by default)?

I currently have the Gii generated code:

public function actionAdmin() {
    $model = new Post('search');
    $model->unsetAttributes();
    if (isset($_GET['Post']))
        $model->attributes = $_GET['Post'];

    $this->render('admin', array(
        'model' => $model,
    ));

Please help. Thanks.

标签: php yii
2条回答
再贱就再见
2楼-- · 2019-07-30 20:46

You can try the corresponding class Post (in protected/models/Post.php) and find the search function. This is where the search area's content is controlled.

Try this:

$criteria->order("create_time desc");

Or refer to: http://www.yiiframework.com/doc/api/1.1/CDbCriteria

查看更多
Emotional °昔
3楼-- · 2019-07-30 21:03

If you set the order as part of the query you won't be able to use the column sorters. You need to update the sort property where the data provider gets created, which in this case is probably in the function @xiaohan2012 mentioned. It would look something like:

    return new CActiveDataProvider('Post', array(
        'criteria'=>$criteria,
        'sort'=>array(
            'defaultOrder'=>'update_time DESC',
        ),
    ));

OR to create a totally custom sort, you would need to create a new sort object something like:

    $sort = new CSort();
    $sort->defaultOrder = 'update_time DESC';
    $sort->attributes = array(
        'post_name'=>array(
            'asc'=>'post_name asc',
            'desc'=>'post_name desc',
        ),
        'update_time'=>array(
            'asc'=>'update_time desc',
            'desc'=>'update_time asc',
        ),
        [... additional columns]
    );

in which case, your data provider would look something like:

    return new CActiveDataProvider('Post', array(
        'criteria'=>$criteria,
        'sort'=>$sort,
    ));
查看更多
登录 后发表回答