How to create pager in Yii2?
Asked Answered
M

4

19

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.

Mylesmylitta answered 28/4, 2014 at 8:36 Comment(0)
C
53

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,
]);
Capsulize answered 28/4, 2014 at 17:59 Comment(3)
Hi Alex - where do you provide the pageSize in your second example. Thanks.Principalities
@Capsulize shouldn't it be 'pagination' => $pagination in the second example?Erastatus
Just a hint: if you use GridView for listing entity rows it's enough to use the data provider code, the widget adds pager html on it's own.Somersault
D
4

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,
]);
Damiano answered 26/9, 2015 at 20:0 Comment(0)
C
0

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/

Commemoration answered 21/6, 2018 at 13:55 Comment(0)
B
0

In your controller

$searchModel = new CourseModuleMasterSearch();   

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

$dataProvider->pagination = ['pageSize' => 20];//add this line
Boanerges answered 20/7, 2019 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.