Yii2 ListView Example: Sample Codes

 ·  · 

Sample codes for demonstrating how to use Yii2 ListView.

 

1 Create A Demo Controller

First of all, create a demo controller, for example, ListController.

So, we need a ListController and a view file for it.

  • YOUR_APP/controllers/ListController.php
  • YOUR_APP/views/list/index.php

You can create these files manually or by Gii module of Yii2.

 

2 Prepare Faked Models

I won't use database in my demo for simplicity. I will create a simple ArrayDataProvider with faked models.

The codes in ListController.php look like this:

<?php
// YOUR_APP/controllers/ListController.php

/* change namespace in your app */
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\ArrayDataProvider;

class ListController extends Controller
{
    public function actionIndex()
    {
        $provider = new ArrayDataProvider([
            'allModels' => $this->getFakedModels(),
            'pagination' => [
                'pageSize' => 5
            ],
            'sort' => [
                'attributes' => ['id'],
            ],
        ]);

        return $this->render('index', ['listDataProvider' => $provider]);
    }

    // function to generate faked models, don't care about this.
    private function getFakedModels()
    {
        $fakedModels = [];

        for ($i = 1; $i < 18; $i++) {
            $fakedItem = [
                'id' => $i,
                'title' => 'Title ' . $i,
                'image' => 'http://placehold.it/300x200'
            ];

            $fakedModels[] = $fakedItem;
        }

        return $fakedModels;
    }
}
?>

 

3 Render ListView

Now it's ready to render model list using ListView in view file.

3.1 Partial Templates

Besides the default YOUR_APP/views/list/index.php view file. I'd like to create two partial templates files. One is for rendering list item, the other is for rendering advertisement.

  • YOUR_APP/views/list/_list_item.php
  • YOUR_APP/views/list/_ad.php

And codes in partial templates are as follows:

<?php
// YOUR_APP/views/list/_list_item.php

use yii\helpers\Html;
?>

<article class="list-item col-sm-12" data-key="<?= $model['id'] ?>">
    <h3><?= Html::encode($model['title']); ?></h3>
    <figure>
        <img src="<?= $model['image'] ?>" alt="<?= Html::encode($model['title']); ?>">
    </figure>
</article>
<?php
// YOUR_APP/views/list/_ad.php
?>

<div class="list-item col-sm-12 ad-item">
    <p>AD</p>
    <img src="http://placehold.it/468x60" alt="">
</div>

3.2 Main View Template

We will use partial templates above as itemView of ListView.

<?php
// YOUR_APP/views/list/index.php

use yii\widgets\ListView;
?>

<div class="row">
    <?= ListView::widget([
        'options' => [
            'tag' => 'div',
        ],
        'dataProvider' => $listDataProvider,
        'itemView' => function ($model, $key, $index, $widget) {
            $itemContent = $this->render('_list_item',['model' => $model]);

            /* Display an Advertisement after the first list item */
            if ($index == 0) {
                $adContent = $this->render('_ad');
                $itemContent .= $adContent;
            }

            return $itemContent;

            /* Or if you just want to display the list item only: */
            // return $this->render('_list_item',['model' => $model]);
        },
        'itemOptions' => [
            'tag' => false,
        ],
        'summary' => '',

        /* do not display {summary} */
        'layout' => '{items}{pager}',

        'pager' => [
            'firstPageLabel' => 'First',
            'lastPageLabel' => 'Last',
            'maxButtonCount' => 4,
            'options' => [
                'class' => 'pagination col-xs-12'
            ]
        ],

    ]);
    ?>
</div>

 

4 Test

Test it by accessing: http://your_host_or_app/index.php?r=list/index.

 

5 Source Code

Source code is available on GitHub.