How to use pagination in Yii Framework 2.0

Hi guys. In this tutorial I will show how you can add pagination in your Yii Framework 2.0 project. To create this tutorial, I will follow the documentation of Yii Framework.

First of all, you must create a new database, and add this code:

CREATE TABLE `country` (
`code` CHAR(2) NOT NULL PRIMARY KEY,
`name` CHAR(52) NOT NULL,
`population` INT(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

to create a new table.

Now you must insert data by using this code:

INSERT INTO `country` VALUES ('AU','Australia',18886000);
INSERT INTO `country` VALUES ('BR','Brazil',170115000);
INSERT INTO `country` VALUES ('CA','Canada',1147000);
INSERT INTO `country` VALUES ('CN','China',1277558000);
INSERT INTO `country` VALUES ('DE','Germany',82164700);

INSERT INTO `country` VALUES ('FR','France',59225700);
INSERT INTO `country` VALUES ('GB','United Kingdom',59623400);
INSERT INTO `country` VALUES ('IN','India',1013662000);
INSERT INTO `country` VALUES ('RU','Russia',146934000);
INSERT INTO `country` VALUES ('US','United States',278357000);

Open the file config/db.php and change the parameters to be correct for your database.

Create a new model and add this code:

public function actionEntry()
{
$query = Country::find();

$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count(),
]);

$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();

return $this->render('entry', [
'countries' => $countries,
'pagination' => $pagination,
]);
}

Create a new php file in your views, called entry.php and add this code:

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($countries as $country): ?> // this code will display the data from your database
<li>
<?= Html::encode("{$country->name} ({$country->code})") ?>:
<?= $country->population ?>
</li>
<?php endforeach; ?>
</ul>

<?= LinkPager::widget(['pagination' => $pagination]) ?> // this code will display the pagination

Now, go to http://localhost/yii/web/index.php?r=site%2Fentry and you will see the data from your database!

Video tutorial:

As you can see, Yii Framework considerably facilitates the work of a programmer.









Leave a Comment