Skip to main content

1:1 relatie in eigen View

Tot nu hebben we gebruik gemaakt van de GridView om data te laten zien (localhost:8080/country/index) - in deze les gaan we onze eigen view maken. In onze eigen view gaan we ook twee tabellen verbinden en laten we in één overzicht gegevens uit de tabel Country en de tabel Cities zien.

Controller

Om te beginnen maken we een nieuwe method in de CountryControllercontrollers/CountryController class.

    public function actionOverzicht()
    {
        $this->view->title = 'Search Countries';

        $query=Country::find();

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

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

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

View

 Dan zetten we in de file views/country/overzicht.php het volgende

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>

<div class="card">
  <div class="card-body">
  <h3 class="card-title">Countries</h5>

    <table class="table" style="width: 70rem;" border=0>
      <tr>
          <th scope="col" style="width: 10rem;">Country</th>
          <th scope="col" style="width: 5rem;">Code</th>
          <th scope="col" style="width: 10rem;">Capital</th>
          <th scope="col" style="text-align: right;width: 10rem;">Population</th>

      </tr>
      <?php foreach ($countries as $country): ?>
        <tr>
            <td><?= $country->Name ?></td>
            <td><?= $country->Code ?></td>
            <td><?
              if ($country->capital) { // note: Antartica has no Capital
                  echo $country->capital->Name;
              } else {
                echo "-";
              }
            ?></td>
            <td style="text-align: right"><?= number_format($country->Population, 0, ',', ' '); ?></td>
        </tr>
      <?php endforeach; ?>
    </table>

  </div>
</div>

<?= LinkPager::widget(['pagination' => $pagination]) ?>