yii2-分頁

胡勇健發表於2024-03-30

yii2-分頁

使用ActiveDataProvider 和 GridView

controller

yii2-分頁
public function actionIndex(){
        $dataProvider = new ActiveDataProvider([
            'query' => ArticleClass::find(),
            'pagination' => [
                'pagesize' => '2',
             ]
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
}

view

yii2-分頁
<?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中引入分頁渲染

控制器

yii2-分頁
    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,
        ]);

    }

檢視

yii2-分頁
<?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'
    ],
]);?>