李记辉 2015-05-22 17:34:56 3957次浏览 0条评论 1 0 0

(1)在控制器中引入 use yii\data\Sort;use yii\data\Pagination;
(2)在actionIndex(我当前控制器ID)写入:

 $sort = new Sort([
    'attributes' => [
        'title'=> [
            'asc' => [
                'title' => SORT_ASC
                ],
            'desc' =>[
                'title' => SORT_DESC
            ],
            'default' => SORT_DESC,
            'label' => '标题',
        ],
        'id'=>  [
            'asc' => [
                'id' => SORT_ASC
                ],
            'desc' =>[
                'id' => SORT_DESC
            ],
            'default' => SORT_DESC,
            'label' => '编号',
        ],
        'alias' =>  [
            'asc' => [
                'alias' => SORT_ASC
                ],
            'desc' =>[ 
                'alias' => SORT_DESC
            ],
            'default' => SORT_DESC,
            'label' => '别名',
        ],
        'content' => [
            'asc' => [
                'content' => SORT_ASC
                ],
            'desc' =>[ 
                'content' => SORT_DESC
            ],
            'default' => SORT_DESC,
            'label' => '内容',
        ],
    ],
]);

在使用分页时加入:

$model = $query->offset($pages->offset)
    ->limit($pages->limit)
    ->orderBy($sort->orders) //添加sort
    ->all();
return $this->render('index', [
    'model' => $model,
    'pages' => $pages,
    'sort' => $sort,  //渲染视图index.php
]);

在视图中:

<tr class="tb_header">
    <th>
        <?php 
        echo $sort->link('id');
        ?>	
    </th>
    <th>
        <?php 
        echo $sort->link('title');
        ?>
    </th>
    <th>
        <?php 
        echo $sort->link('alias');
        ?>
    </th>
    <th>
        <?php 
        echo $sort->link('content');
        ?>
    </th>
    <th>
        <font color="#337AC4">操作</font>//为了统一添加一个颜色值
    </th>
</tr>
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册