How to create pager in Yii2?

2020-05-19 09:21发布

I was searching how to create pager in Yii2 using LinkPage widget.

Is there any example? I am new in Yii, so any help would be good.

标签: php pager yii2
4条回答
一纸荒年 Trace。
2楼-- · 2020-05-19 09:46

It is simple

$dataProvider = new ActiveDataProvider([
    'query' => User::find(),
    'pagination' => array('pageSize' => 50),
]);

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

Or if you don't use dataProvider you should use this:

$query = User::find();
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>30]);

echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]);
查看更多
小情绪 Triste *
3楼-- · 2020-05-19 09:48

In your controller

$searchModel = new CourseModuleMasterSearch();   

$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

$dataProvider->pagination = ['pageSize' => 20];//add this line
查看更多
Melony?
4楼-- · 2020-05-19 09:54

In controller:

function actionIndex()
{
    $query = Article::find()->where(['status' => 1]);
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    $models = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

    return $this->render('index', [
         'models' => $models,
         'pages' => $pages,
    ]);
}

In view file:

foreach ($models as $model) {
    // display $model here
}

// display pagination
echo LinkPager::widget([
    'pagination' => $pages,
]);
查看更多
孤傲高冷的网名
5楼-- · 2020-05-19 09:57

Below is too simple for adding pagination,

We just need to add in controller,

$dataProvider = new ActiveDataProvider([
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
]);

Yii2 will bring pagination on index page, https://yii2-framework.readthedocs.io/en/stable/guide/output-data-widgets/

查看更多
登录 后发表回答