Codxplore.com

Latest news:

Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now https://play.google.com/store/apps/details?id=com.akramhossin.bukharisharif

Yii2 pagination


Yii2 pagination

Today we will discuss how to implement pagination to any Yii2 web application.

The pagination represents information relevant to pagination of data items fetch from any data sources.

When we need data to be rendered in multiple pages,this can be used to display information such as total item count, page size, current page.

Pagination implementation has two steps.

  • Fetch data from data source from controller
  • Pass data from controller to view page

The following example shows how to create a pagination object and feed it to a pager.

In the controller section we need to do following. Lets say we have an action name as actionSearch, this method

will fetch data from MySQL database and pass to view page.To accomplish this we can use below code

public function actionSearch() {
       $query = Blog::find()
                ->select([
                    'tbl_blog.*',
                    'tbl_blog.total_view as views',
                    'tbl_user.displayName',
                    'DATE_FORMAT(tbl_blog.date, "%M %d,%Y,%h:%i %p") as date_formated'
                ])
                ->join('LEFT JOIN', 'tbl_user', 'tbl_blog.userId = tbl_user.userid')
                ->orderBy(['blogId' => SORT_DESC]);
        $countQuery = clone $query;
        $pages = new Pagination([
            'totalCount' => $countQuery->count(),
            'pageSize' => 12,
            'route' => '/site/item-list',
        ]);

        $models = $query->offset($pages->offset)
            ->limit($pages->limit)
            ->asArray()
            ->all();
      

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

}


in the view page we will use this code to display data passed from controller and pager

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

// display pagination
echo yiiwidgetsLinkPager::widget([
    'pagination' => $pages,
 ]);

For reference please visit

http://www.yiiframework.com/doc-2.0/yii-data-pagination.html

Tags : PHP, Yii2,

Views : 3179

Subscribe Us


Follow Us