dmodai 2016-04-26 18:13:02 5258次浏览 1条评论 2 2 0

1、查找模型后进行分页(默认用GridView::widget 中分页)
postSearch.php搜索模型

$query = Post::find()->orderBy('id DESC');
$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'pagination'=>[
      'pageSize' => 2,
    ],
    'sort'=>[
      'defaultOrder'=>[
        'id'=> SORT_DESC,
        'title'=> SORT_ASC,
      ]
    ]
]);

PostController

$searchModel = new postSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
    'searchModel' => $searchModel,
    'dataProvider' => $dataProvider,
]);

以上是在GridView::widget 中使用默认布局和分页

现在如果不想用默认分页,可以

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'pager'=>[
        'options'=>['class'=>'hidden']
    ],
]) ?>

然后在需要显示分页的地方

<?= \yii\widgets\LinkPager::widget([
    'pagination' => $dataProvider->getPagination(),
]); ?>

2、全部使用自定义的分页

$query = Post::find();
$countQuery = clone $query;
$pages = new Pagination([
    'totalCount' =>$countQuery->count(),
    'pageSize' => '2'
]);
$models = $query->offset($pages->offset)
    ->limit($pages->limit)
    ->OrderBy(['status'=>SORT_DESC])
    ->all();
$this->render('index', [
   'models'=>$models,
   'pages'=>$pages,
]); 

视图:

//单独展示分页 
<?= LinkPager::widget([
    'pagination'=>$pages,
]) ?>

初学几天,有不对的地方请多多指正

觉得很赞
您需要登录后才可以评论。登录 | 立即注册