How to create pager in Yii2?

社会主义新天地 提交于 2019-12-03 05:55:17

问题


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.


回答1:


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



回答2:


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



回答3:


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/




回答4:


In your controller

$searchModel = new CourseModuleMasterSearch();   

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

$dataProvider->pagination = ['pageSize' => 20];//add this line


来源:https://stackoverflow.com/questions/23336269/how-to-create-pager-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!