下面介绍一下 Activedataprovider 类分页的使用

  1. use yii\data\ActiveDataProvider; 这是必须的步骤,因为我们要使用 ActiveDataProvider
  2. use common\models\User;
  3. public function actionList()
  4. {
  5. $model = new User();
  6. $dataProvider = new ActiveDataProvider([
  7. 'query' => $model->find(),
  8. 'pagination => [
  9. 'pagesize' => '10',
  10. ]
  11. ]);
  12. return $this->render('list', ['model' => $model, 'dataProvider' => $dataProvider]);
  13. }

view代码
list.php

  1. use yii\grid\GridView; 这是必须的;
  2. GridView::widget([
  3. 'dataProvider' => $dataProvider,
  4. 'columns' => [
  5. 'attribute',(attribute为字段的名称,开发时候根据自己的需要进行修改)
  6. [
  7. 'attribute' => 'create_time',
  8. 'format' => ['data', 'Y-m-d H:i:s'],
  9. 'options' => ['width' => '200']
  10. ]],
  11. ['class' => 'yii\grid\ActionColumn', 'header' => '操作', 'headerOptions' => ['width' => '80']],
  12. ]);

下面为大家介绍第二种分页方法:

控制器 CommentController 里面的任意一个方法,在这里我的方法是 actionComment();

  1. <?php
  2. use yii\data\Pagination;
  3. use app\models\Comment;
  4. public function actionComment(){
  5. $data = Comment::find()->andWhere(['id' => '10']);
  6. $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => '2']);
  7. $model = $data->offset($pages->offset)->limit($pages->limit)->all();
  8. return $this->render('comment',[
  9. 'model' => $model,
  10. 'pages' => $pages,
  11. ]);
  12. }
  13. ?>

好的,到这里,控制器部分基本就结束了。我们接续看 view 里面的代码:

Comment.php 文件代码如下所示

  1. <?php
  2. use yii\widgets\LinkPager;
  3. ?>
  4. foreach($model as $key=>$val)
  5. {
  6. 这里就是遍历数据了,省略......
  7. }
  8. <?= LinkPager::widget(['pagination' => $pages]); ?>

参考: http://blog.sina.com.cn/s/blog_88a65c1b0101j0md.html
参考: http://blog.sina.com.cn/s/blog_88a65c1b0101ixhw.html

分类: web

标签:   yii2