分页(一)
下面介绍一下 Activedataprovider 类分页的使用
use yii\data\ActiveDataProvider; 这是必须的步骤,因为我们要使用 ActiveDataProvider 类
use common\models\User;
public function actionList()
{
$model = new User();
$dataProvider = new ActiveDataProvider([
'query' => $model->find();
'pagination => [
'pagesize' => '10',
]
]);
return $this->render('list', ['model' => $model, 'dataProvider' => $dataProvider]);
}
view代码
list.php
use yii\grid\GridView; 这是必须的;
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'attribute',(attribute为字段的名称,开发时候根据自己的需要进行修改)
[
'attribute' => 'create_time',
'format' => ['data', 'Y-m-d H:i:s'],
'options' => ['width' => '200']
]],
['class' => 'yii\grid\ActionColumn', 'header' => '操作', 'headerOptions' => ['width' => '80']],
]);
分页(二)
控制器 CommentController 里面的任意一个方法,在这里我的方法是 actionComment();
<?php
use yii\data\Pagination;
use app\models\Comment;
public function actionComment(){
$data = Comment::find()->andWhere(['id' => '10']);
$pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => '2']);
$model = $data->offset($pages->offset)->limit($pages->limit)->all();
return $this->render('comment',[
'model' => $model,
'pages' => $pages,
]);
}
?>
好的,到这里,控制器部分基本就结束了。我们接续看 view 里面的代码:
Comment.php 文件代码如下所示
<?php
use yii\widgets\LinkPager;
?>
foreach($model as $key=>$val)
{
遍历数据,省略......
}
<?= LinkPager::widget(['pagination' => $pages]); ?>