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.

zishe
  • 10,665
  • 12
  • 64
  • 103
newYii
  • 193
  • 1
  • 1
  • 4

4 Answers4

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,
]);
Alex
  • 8,055
  • 7
  • 39
  • 61
  • Hi Alex - where do you provide the pageSize in your second example. Thanks. – Pawan Jan 11 '15 at 12:38
  • 1
    @Alex shouldn't it be `'pagination' => $pagination` in the second example? – Felipe Jan 21 '15 at 01:52
  • 1
    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. – drakonli Feb 20 '15 at 21:06
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,
]);
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Nizar Ali Hunzai
  • 257
  • 1
  • 2
  • 8
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/

Jothi
  • 1
0

In your controller

$searchModel = new CourseModuleMasterSearch();   

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

$dataProvider->pagination = ['pageSize' => 20];//add this line
MatejMecka
  • 1,448
  • 2
  • 24
  • 37