yii2-分页

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'
    ],
]);?>
posted @ 2024-03-30 14:47  胡勇健  阅读(24)  评论(0编辑  收藏  举报