Yii2 provides powerful widgets for displaying and managing data in a structured format. The two primary widgets used for this purpose are GridView and ListView. These widgets work seamlessly with Yii2's ActiveDataProvider and ArrayDataProvider, making it easy to integrate data with pagination, sorting, and filtering.
GridView is used to display tabular data. It provides built-in features such as sorting, pagination, column customization, and action buttons.
To use GridView, you need a DataProvider. The most common type is ActiveDataProvider, which fetches data from an ActiveRecord model.
use yii\grid\GridView;
use yii\data\ActiveDataProvider;
use app\models\User;
$dataProvider = new ActiveDataProvider([
'query' => User::find(),
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'id' => SORT_DESC,
]
],
]);
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
'email',
'created_at:datetime',
['class' => 'yii\grid\ActionColumn'],
],
]);You can customize GridView columns in multiple ways.
Automatically generates serial numbers.
['class' => 'yii\grid\SerialColumn'],Displays data from specific model attributes.
'username',
'email:email', // Formats the column as an email link
'created_at:datetime', // Formats as datetimeDisplays action buttons like view, update, and delete.
['class' => 'yii\grid\ActionColumn'],You can create custom columns by defining a value function.
[
'label' => 'Full Name',
'value' => function ($model) {
return $model->first_name . ' ' . $model->last_name;
},
]You can enable filtering by using search models.
'filter' => Html::activeTextInput($searchModel, 'username', ['class' => 'form-control'])ListView is used for displaying data in a flexible layout, such as lists, cards, or custom templates.
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
use app\models\Post;
$dataProvider = new ActiveDataProvider([
'query' => Post::find(),
'pagination' => [
'pageSize' => 5,
],
]);
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_post', // Refers to the partial view file _post.php
]);_post.php)/* @var $model app\models\Post */
?>
<div class="post">
<h3><?= $model->title ?></h3>
<p><?= $model->content ?></p>
</div>You can modify the layout of ListView.
'layout' => "{summary}\n{items}\n{pager}",| Feature | GridView | ListView |
|---|---|---|
| Tabular Format | Yes | No |
| Custom Templates | No | Yes |
| Sorting | Yes | Yes |
| Pagination | Yes | Yes |
| Filtering | Yes | No |
GridView is best for structured tabular data, while ListView is better for custom layouts and flexible designs.
Yii2 GridView provides a highly customizable way to display data. Below are some advanced options, including custom buttons, column formatting, and additional configurations.
You can customize the table's appearance by setting class names and formatting options:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => 'N/A'], // Custom null display
'tableOptions' => ['class' => 'table table-bordered table-striped'], // Table styling
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
'email',
['class' => 'yii\grid\ActionColumn'],
],
]);Yii2 allows formatting data using predefined formats such as text, html, boolean, date, etc.
[
'attribute' => 'created_at',
'format' => ['date', 'php:Y-m-d H:i:s'],
],
[
'attribute' => 'is_active',
'format' => 'boolean',
],| Format Name | Description |
|---|---|
text | Displays plain text (default) |
html | Renders HTML content |
boolean | Displays Yes/No for boolean values |
date | Formats a date value |
datetime | Formats a datetime value |
currency | Formats numbers as currency |
email | Converts text into a mailto: link |
url | Converts text into a hyperlink |
Show a delete button only when the logged-in user created the entry.
[
'header' => 'Remove',
'value' => function ($model) {
if ($model->created_by == Yii::$app->user->identity->id) {
return Html::a(
'<i class="fa fa-trash"></i>',
['remove', 'id' => $model->id],
['class' => 'btn btn-danger', 'data-confirm' => 'Are you sure you want to delete this?']
);
}
},
'format' => 'raw',
'contentOptions' => ['style' => 'width: 5%', 'class' => 'text-center'],
],Use Html::img() inside a format => 'raw' column.
[
'header' => 'Image',
'value' => function ($model) {
return Html::button(
Html::img(Url::to(['viewimage', 'photo_id' => $model->id, 'image' => $model->path]), [
'style' => 'height:50px; width:auto;',
'alt' => 'Image'
]),
['value' => Url::to(['fullview', 'photo_id' => $model->id]), 'class' => 'btn popupButton']
);
},
'format' => 'raw',
],You can modify the action buttons (view, update, delete) in ActionColumn:
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete} {custom}',
'buttons' => [
'custom' => function ($url, $model) {
return Html::a('<i class="fa fa-file"></i>', ['export', 'id' => $model->id], [
'title' => 'Export Data',
'class' => 'btn btn-success'
]);
},
],
],To highlight specific rows based on a condition, use rowOptions:
'rowOptions' => function ($model) {
if ($model->status == 'inactive') {
return ['class' => 'danger']; // Bootstrap class for red background
}
return [];
},group Feature)[
'attribute' => 'category',
'group' => true, // This will merge the same category rows
],Both GridView and ListView are essential Yii2 widgets for displaying data. Use GridView for tabular data and ListView for flexible layouts. By combining these widgets, you can create powerful data-driven applications in Yii2.
Sign in to join the discussion and post comments.
Sign in