ActiveRecord
If you're going to work with records using Yii, it's helpful to make use of the ActiveRecord class. In this example, we're working with a database of country data. Thankfully, this is a simple scenario which requires the creation of a simple class. Just add this as models/Country.php<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
}
Controller
Next we need to create a controller which we can use to pass data from the Country ActiveRecord model to a view. In this case, we're also going to add some pagination functionality, which we'll also pass to the view.- First we create a $query object which will be used to retrieve the data.
- Next we create a $pagination object which will be used to control the display of that data.
- Next we get all the data we want.
- Finally we pass the data and pagination objects to the view.
We save this class as controllers/CountryController.php
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
{
public function actionIndex()
{
$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('index', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
}
View
The view performs 3 tasks in this process:Loops through the data, adding it to the page.
Adding the pagination object to that the data can be paged through.
Adding the LinkPager widget object to the pagination object to automatically create all those links, saving us a bunch of coding.
We'll put the view in the directory views/country/index.php
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($countries as $country): ?>
<li>
<?php echo Html::encode("{$country->code} ({$country->name})"); ?>:
<?php echo $country->population; ?>
</li>
<?php endforeach; ?>
</ul>
<?php echo LinkPager::widget(['pagination' => $pagination]); ?>
No comments:
Post a Comment