yii2-分頁
使用ActiveDataProvider 和 GridView
controller
public function actionIndex(){
$dataProvider = new ActiveDataProvider([
'query' => ArticleClass::find(),
'pagination' => [
'pagesize' => '2',
]
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
view
<?php
use yii\grid\GridView;
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'layout' => "{summary}{items}{pager}",
'summary' => "第{begin}-{end}條,共{totalCount}條資料",
'tableOptions' => [
'class' => 'table table-hover',
],
'pager' => [
'firstPageLabel' => "首頁",
'prevPageLabel' => '上一頁',
'nextPageLabel' => '下一頁',
'lastPageLabel' => '尾頁',
'linkContainerOptions' => ['class' => 'page-item'],
'linkOptions' => ['class' => 'page-link'],
'disabledListItemSubTagOptions' => [
'tag' => 'a',
'href' => 'javascript:;',
'tabindex' => '-1',
'class' => 'page-link'
],
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'drive',
'base_url',
'path'
]
]); ?>
控制器中引入分頁類,並在views中引入分頁渲染
控制器
public function actionIndex()
{
$query = Attachment::find();
$countQuery = clone $query;
$pageSize = 2;
$pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => $pageSize]);
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
return $this->render('index', [
'models' => $models,
'pages' => $pages,
]);
}
檢視
<?php
use yii\widgets\LinkPager;
?>
<?php
//迴圈展示資料
foreach ($models as $model) {
echo "<li>".$model['id'].' | ' .$model['drive']. ' | ' .$model['base_url']."</li>";
}
?>
<?= LinkPager::widget([
'pagination' => $pages,
'nextPageLabel' => '下一頁',
'prevPageLabel' => '上一頁',
'firstPageLabel' => '首頁',
'lastPageLabel' => '尾頁',
'linkContainerOptions' => ['class' => 'page-item'],
'linkOptions' => ['class' => 'page-link'],
'disabledListItemSubTagOptions' => [
'tag' => 'a',
'href' => 'javascript:;',
'tabindex' => '-1',
'class' => 'page-link'
],
]);?>