Yii2 ListView Example

By:   –  Last updated:   –  #yii2 ·  #php

Code Theme [Dark]

Content Overview [Hide]

Yii2 ListView is a widget used to render data list. It is very convenient to display data along with pagination using a combination of Yii2 ActiveDataProvider and Yii2 ListView. Furthermore ListView can be easily customized by its configuring options. This tutorial will give basic example of using Yii2 ListView.

1 Preparing

First of all, you should create a Yii2 project and prepare a data source, which will be rendered by ListView.

Pretend that there is a database table named "post" which has some dummy testing data, and we have created a Yii2 model class "Post" for it. Then in our PostController we add an action to response the "list" request.

// PostController.php
use app\models\Post;

class PostController extends \yii\web\Controller
    public function actionList()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Post::find()->where(['status' => 1])->orderBy('id DESC'),
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

        $this->view->title = 'Posts List';
        return $this->render('list', ['listDataProvider' => $dataProvider]);
    }
}

Action above will response the request url: /index.php?r=post/list, and render the template list.php under project folder your_project_folder/views/post/. Let's see how to render the data list in list.php.

2 ListView Configurations

For simple case, you just echo ListView and pass the dataProvider to it in list.php view file, and that's done!

/* list.php view file*/

<?= 
ListView::widget([
    'dataProvider' => $listDataProvider,
]); 
?>

But in this way the ListView only display a list of id number. By default it will echo a list of model keys. So we need add more configurations to customize the output of rendering. Following picture outlines an overview of the most important configuring options of Yii2 ListView.

yii2_listview_config

2.1 dataProvider

dataProvider is used to set the data source , it must be an object that implementing yii\data\DataProviderInterface. Usually it is an instance of ActiveDataProvider class.

2.2 options

options is an array to set html attributes of the ListView outer wrapper tag. For example:

<?= 
ListView::widget([
    'dataProvider' => $listDataProvider,
    'options' => [
        'tag' => 'div',
        'class' => 'list-wrapper',
        'id' => 'list-wrapper',
    ],
]);
?>

2.3 layout

layout specifies the highlevel layout of ListView markup. By default its value is an string: "{summary}\n{items}\n{pager}". That means firstly render a ListView summary header, then followed with ListView items, and the pager at last. You can override this easily, for example, to move up the pager and move down the summary, sample codes:

<?= 
ListView::widget([
    'dataProvider' => $listDataProvider,
    'options' => [
        'tag' => 'div',
        'class' => 'list-wrapper',
        'id' => 'list-wrapper',
    ],
    'layout' => "{pager}\n{items}\n{summary}",
]);
?>

2.4 itemView

itemView can be either a string or an callback function. Its job is to tell ListView how to render each list item with the model data.

2.4.1 Pass A String

If pass a string to it ,the string must be file name of an template partial. For example we can create a _list_item.php template partial to define html markup for each list item, then we pass the partial file name _list_item to itemView.

<?= 
ListView::widget([
    'dataProvider' => $listDataProvider,
    'options' => [
        'tag' => 'div',
        'class' => 'list-wrapper',
        'id' => 'list-wrapper',
    ],
    'layout' => "{pager}\n{items}\n{summary}",
    'itemView' => '_list_item',
]);
?>

In this configuring way, there will be four variants implicitly passed into and available in _list_item partial template:

  • $model, the data model item.
  • $key, the key value associated with the data item.
  • $index, the zero-based index of the data item in the items array returned by $dataProvider.
  • $widget, ListView widget instance itself.
2.4.2 Pass A Callback

Alternatively, you can pass a callback to itemView and this callback will be called each time the list item is renderd.

<?=
ListView::widget([
    'dataProvider' => $listDataProvider,
    'options' => [
        'tag' => 'div',
        'class' => 'list-wrapper',
        'id' => 'list-wrapper',
    ],
    'layout' => "{pager}\n{items}\n{summary}",
    'itemView' => function ($model, $key, $index, $widget) {
        return $this->render('_list_item',['model' => $model]);

        // or just do some echo
        // return $model->title . ' posted by ' . $model->author;
    },
]);
?>

The callback function signature shoule like below, and the four parameters are exactly the same as the implicite variants explained above.

function ($model, $key, $index, $widget)

The item template _list_item.php may look like this:

<?php
// _list_item.php
use yii\helpers\Html;
use yii\helpers\Url;
?>

<article class="item" data-key="<?= $model->id; ?>">
    <h2 class="title">
    <?= Html::a(Html::encode($model->title), Url::toRoute(['post/show', 'id' => $model->id]), ['title' => $model->title]) ?>
    </h2>

    <div class="item-excerpt">
    <?= Html::encode($model->excerpt); ?>
    </div>
</article>
2.4.3 When And Why

So when should we pass a callback to itemView? I think under following scenarios it is much convenient to use a callback for itemView.

  • Change or format model data before rendering it;
  • Hack the normal rendering flow. For example, by using $index, we can insert an advertisement following the first three items;
  • Render different partial templates. For instance we can render text template, image template, or video template according to the model's category field.

2.5 pager

pager is used to configure the pagination markup. By default Yii2 use Bootstrap pagination component layout and style to render the pagination of ListView. But you can add your own settings to customize it.

ListView::widget([
    'dataProvider' => $listDataProvider,
    'options' => [
        'tag' => 'div',
        'class' => 'list-wrapper',
        'id' => 'list-wrapper',
    ],
    'layout' => "{pager}\n{items}\n{summary}",
    'itemView' => function ($model, $key, $index, $widget) {
        return $this->render('_list_item',['model' => $model]);

        // or just do some echo
        // return $model->title . ' posted by ' . $model->author;
    },
    'pager' => [
        'firstPageLabel' => 'first',
        'lastPageLabel' => 'last',
        'nextPageLabel' => 'next',
        'prevPageLabel' => 'previous',
        'maxButtonCount' => 3,
    ],
]);

The pager is abstracted to a class named yii\widgets\LinkPager. For more customizing options of ListView pager, please refer to Yii2 official document about LinkPager.

3 Summary

To sum up, we have sample codes for customizing Yii2 ListView now. Following is the source codes put together.

<?= 
ListView::widget([
    'dataProvider' => $listDataProvider,
    'options' => [
        'tag' => 'div',
        'class' => 'list-wrapper',
        'id' => 'list-wrapper',
    ],
    'layout' => "{pager}\n{items}\n{summary}",
    'itemView' => function ($model, $key, $index, $widget) {
        return $this->render('_list_item',['model' => $model]);

        // or just do some echo
        // return $model->title . ' posted by ' . $model->author;
    },
    'itemOptions' => [
        'tag' => false,
    ],
    'pager' => [
        'firstPageLabel' => 'first',
        'lastPageLabel' => 'last',
        'nextPageLabel' => 'next',
        'prevPageLabel' => 'previous',
        'maxButtonCount' => 3,
    ],
]);
?>

4 Demo

Sample codes of how to use ListView: Yii2 ListView Example: Sample Codes