output-data-widgets.md 18.3 KB
Newer Older
Qiang Xue committed
1 2 3
Data widgets
============

4
> Note: This section is under development.
Qiang Xue committed
5

Qiang Xue committed
6 7 8
ListView
--------

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
The ListView widget is used to display data from data provider. Each data model is rendered using the view specified.
Since it provides features such as pagination, sorting and filtering out of the box, it is handy both to display
information to end user and to create data managing UI.

A typical usage is as follows:

```php
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;

$dataProvider = new ActiveDataProvider([
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
]);
echo ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_post',
]);
```

The `_post` view could be the following:


```php
<?php
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
?>
<div class="post">
    <h2><?= Html::encode($model->title) ?></h2>
    
    <?= HtmlPurifier::process($model->text) ?>    
</div>
```

In the view above current data model is available as `$model`. Additionally the following are available:

- `$key`: mixed, the key value associated with the data item.
- `$index`: integer, the zero-based index of the data item in the items array returned by data provider.
- `$widget`: ListView, this widget instance.

If you need to pass additional data to each view use `$viewParams` like the following:

```php
echo ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_post',
    'viewParams' => [
        'fullView' => true,
    ],
]);
```
Qiang Xue committed
63 64 65 66 67 68 69 70 71 72


DetailView
----------

DetailView displays the detail of a single data [[yii\widgets\DetailView::$model|model]].
 
It is best used for displaying a model in a regular format (e.g. each model attribute is displayed as a row in a table).
The model can be either an instance of [[\yii\base\Model]] or an associative array.
 
73
DetailView uses the [[yii\widgets\DetailView::$attributes]] property to determine which model attributes should be displayed and how they
Qiang Xue committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
should be formatted.
 
A typical usage of DetailView is as follows:
 
```php
echo DetailView::widget([
    'model' => $model,
    'attributes' => [
        'title',             // title attribute (in plain text)
        'description:html',  // description attribute in HTML
        [                    // the owner name of the model
            'label' => 'Owner',
            'value' => $model->owner->name,
        ],
    ],
]);
```


GridView
--------
95

96
Data grid or GridView is one of the most powerful Yii widgets. It is extremely useful if you need to quickly build the admin
97
section of the system. It takes data from [data provider](output-data-providers.md) and renders each row using a set of columns
98
presenting data in the form of a table.
99 100

Each row of the table represents the data of a single data item, and a column usually represents an attribute of
101
the item (some columns may correspond to complex expressions of attributes or static text).
102 103

Grid view supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode
104
or as a normal page request. A benefit of using GridView is that when the user disables JavaScript, the sorting and pagination automatically degrade to normal page requests and still function as expected.
105

Anderson Müller committed
106
The minimal code needed to use GridView is as follows:
107 108

```php
109
use yii\grid\GridView;
Alexander Makarov committed
110 111 112
use yii\data\ActiveDataProvider;

$dataProvider = new ActiveDataProvider([
113 114 115 116
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
Alexander Makarov committed
117 118
]);
echo GridView::widget([
119
    'dataProvider' => $dataProvider,
Alexander Makarov committed
120
]);
121 122 123
```

The above code first creates a data provider and then uses GridView to display every attribute in every row taken from
124
the data provider. The displayed table is equipped with sorting and pagination functionality.
125

Qiang Xue committed
126
### Grid columns
127 128 129

Yii grid consists of a number of columns. Depending on column type and settings these are able to present data differently.

130
These are defined in the `columns` part of GridView configuration like the following:
131 132

```php
133
echo GridView::widget([
134 135 136
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
137 138
        // Simple columns defined by the data contained in $dataProvider.
        // Data from the model's column will be used.
139 140 141 142
        'id',
        'username',
        // More complex one.
        [
143
            'class' => 'yii\grid\DataColumn', // can be omitted, as it is the default
144
            'value' => function ($data) {
145
                return $data->name; // $data['name'] for array data, e.g. using SqlDataProvider.
146 147 148
            },
        ],
    ],
149
]);
150 151
```

152
Note that if the `columns` part of the configuration isn't specified, Yii tries to show all possible columns of the data provider's model.
153 154 155

### Column classes

Alexander Makarov committed
156 157 158 159
Grid columns could be customized by using different column classes:

```php
echo GridView::widget([
160 161 162 163 164 165
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn', // <-- here
            // you may configure additional properties here
        ],
Alexander Makarov committed
166 167
```

168
In addition to column classes provided by Yii that we'll review below, you can create your own column classes.
Alexander Makarov committed
169

170
Each column class extends from [[\yii\grid\Column]] so that there are some common options you can set while configuring
Alexander Makarov committed
171 172 173 174
grid columns.

- `header` allows to set content for header row.
- `footer` allows to set content for footer row.
175
- `visible` defines if the column should be visible.
Alexander Makarov committed
176 177
- `content` allows you to pass a valid PHP callback that will return data for a row. The format is the following:

178 179 180 181 182
  ```php
  function ($model, $key, $index, $column) {
      return 'a string';
  }
  ```
Alexander Makarov committed
183

184
You may specify various container HTML options by passing arrays to:
Alexander Makarov committed
185 186 187 188

- `headerOptions`
- `footerOptions`
- `filterOptions`
189
- `contentOptions`
190

191
#### Data column <a name="data-column"></a>
192

193
Data column is used for displaying and sorting data. It is the default column type so the specifying class could be omitted when
Alexander Makarov committed
194 195
using it.

196 197
The main setting of the data column is its format. It could be specified via `format` attribute. Its values
correspond to methods in the `formatter` [application component](structure-application-components.md) that is [[\yii\i18n\Formatter|Formatter]] by default:
198 199

```php
200
echo GridView::widget([
201 202 203 204
    'columns' => [
        [
            'attribute' => 'name',
            'format' => 'text'
205
        ],
206 207
        [
            'attribute' => 'birthday',
208
            'format' => ['date', 'php:Y-m-d']
209 210
        ],
    ],
211
]); 
212
```
213

214 215
In the above, `text` corresponds to [[\yii\i18n\Formatter::asText()]]. The value of the column is passed as the first
argument. In the second column definition, `date` corresponds to [[\yii\i18n\Formatter::asDate()]]. The value of the
216
column is, again, passed as the first argument while 'php:Y-m-d' is used as the second argument value.
217

218 219
For a list of available formatters see the [section about Data Formatting](output-formatter.md).

Alexander Makarov committed
220

221 222
#### Action column

Alexander Makarov committed
223 224 225 226
Action column displays action buttons such as update or delete for each row.

```php
echo GridView::widget([
227 228 229 230 231 232
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'class' => 'yii\grid\ActionColumn',
            // you may configure additional properties here
        ],
Alexander Makarov committed
233 234 235 236 237 238
```

Available properties you can configure are:

- `controller` is the ID of the controller that should handle the actions. If not set, it will use the currently active
  controller.
239
- `template` defines the template used for composing each cell in the action column. Tokens enclosed within curly brackets are
Alexander Makarov committed
240
  treated as controller action IDs (also called *button names* in the context of action column). They will be replaced
241
  by the corresponding button rendering callbacks specified in [[yii\grid\ActionColumn::$buttons|buttons]]. For example, the token `{view}` will be
Alexander Makarov committed
242
  replaced by the result of the callback `buttons['view']`. If a callback cannot be found, the token will be replaced
243
  with an empty string. The default tokens are `{view} {update} {delete}`.
Alexander Makarov committed
244 245 246 247
- `buttons` is an array of button rendering callbacks. The array keys are the button names (without curly brackets),
  and the values are the corresponding button rendering callbacks. The callbacks should use the following signature:

```php
248
function ($url, $model, $key) {
249
    // return the button HTML code
Alexander Makarov committed
250 251 252
}
```

253
In the code above, `$url` is the URL that the column creates for the button, `$model` is the model object being
254
rendered for the current row, and `$key` is the key of the model in the data provider array.
Alexander Makarov committed
255 256

- `urlCreator` is a callback that creates a button URL using the specified model information. The signature of
MarsuBoss committed
257 258
  the callback should be the same as that of [[yii\grid\ActionColumn::createUrl()]]. If this property is not set,
  button URLs will be created using [[yii\grid\ActionColumn::createUrl()]].
Alexander Makarov committed
259

260 261
#### Checkbox column

Alexander Makarov committed
262
CheckboxColumn displays a column of checkboxes.
Qiang Xue committed
263

264
To add a CheckboxColumn to the [[yii\grid\GridView]], add it to the [[yii\grid\GridView::$columns|columns]] configuration as follows:
Qiang Xue committed
265

Alexander Makarov committed
266 267
```php
echo GridView::widget([
268 269 270 271 272 273 274 275
    'dataProvider' => $dataProvider,
    'columns' => [
        // ...
        [
            'class' => 'yii\grid\CheckboxColumn',
            // you may configure additional properties here
        ],
    ],
Alexander Makarov committed
276 277 278 279 280 281 282 283 284 285
```

Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the following
JavaScript code:

```javascript
var keys = $('#grid').yiiGridView('getSelectedRows');
// keys is an array consisting of the keys associated with the selected rows
```

286 287
#### Serial column

Alexander Makarov committed
288 289 290 291 292 293
Serial column renders row numbers starting with `1` and going forward.

Usage is as simple as the following:

```php
echo GridView::widget([
294 295 296
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'], // <-- here
297
        // ...
Alexander Makarov committed
298 299
```

300 301

### Sorting data
302 303 304

- https://github.com/yiisoft/yii2/issues/1576

305
### Filtering data
306

307
For filtering data the GridView needs a [model](structure-models.md) that takes the input from the filtering
308
form and adjusts the query of the dataProvider to respect the search criteria.
309
A common practice when using [active records](db-active-record.md) is to create a search Model class
Mark committed
310 311
that provides needed functionality (it can be generated for you by Gii). This class defines the validation 
rules for the search and provides a `search()` method that will return the data provider.
312

313
To add the search capability for the `Post` model, we can create `PostSearch` like the following example:
314 315 316 317 318 319 320 321 322 323

```php
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

324
class PostSearch extends Post
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
{
    public function rules()
    {
        // only fields in rules() are searchable
        return [
            [['id'], 'integer'],
            [['title', 'creation_date'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = Post::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        // load the seach form data and validate
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        // adjust the query by adding the filters
        $query->andFilterWhere(['id' => $this->id]);
356
        $query->andFilterWhere(['like', 'title', $this->title])
357 358 359 360 361 362 363 364
              ->andFilterWhere(['like', 'creation_date', $this->creation_date]);

        return $dataProvider;
    }
}

```

Carsten Brandt committed
365 366 367 368
You can use this function in the controller to get the dataProvider for the GridView:

```php
$searchModel = new PostSearch();
Mark committed
369
$dataProvider = $searchModel->search(Yii::$app->request->get());
Carsten Brandt committed
370 371

return $this->render('myview', [
372 373
    'dataProvider' => $dataProvider,
    'searchModel' => $searchModel,
Carsten Brandt committed
374 375 376 377 378 379 380 381
]);
```

And in the view you then assign the `$dataProvider` and `$searchModel` to the GridView:

```php
echo GridView::widget([
    'dataProvider' => $dataProvider,
382
    'filterModel' => $searchModel,
Carsten Brandt committed
383 384 385 386
]);
```


387
### Working with model relations
388

389
When displaying active records in a GridView you might encounter the case where you display values of related
390
columns such as the post author's name instead of just his `id`.
Carsten Brandt committed
391 392 393
You do this by defining the attribute name in columns as `author.name` when the `Post` model
has a relation named `author` and the author model has an attribute `name`.
The GridView will then display the name of the author but sorting and filtering are not enabled by default.
394
You have to adjust the `PostSearch` model that has been introduced in the last section to add this functionality.
Carsten Brandt committed
395

396
To enable sorting on a related column you have to join the related table and add the sorting rule
Carsten Brandt committed
397
to the Sort component of the data provider:
398 399 400 401 402 403 404 405 406

```php
$query = Post::find();
$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

// join with relation `author` that is a relation to the table `users`
// and set the table alias to be `author`
407
$query->joinWith(['author' => function($query) { $query->from(['author' => 'users']); }]);
408 409 410 411 412 413 414 415 416 417
// enable sorting for the related column
$dataProvider->sort->attributes['author.name'] = [
    'asc' => ['author.name' => SORT_ASC],
    'desc' => ['author.name' => SORT_DESC],
];

// ...
```

Filtering also needs the joinWith call as above. You also need to define the searchable column in attributes and rules like this:
Carsten Brandt committed
418

419 420 421
```php
public function attributes()
{
Carsten Brandt committed
422 423
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['author.name']);
424 425 426 427 428 429 430 431 432 433
}

public function rules()
{
    return [
        [['id'], 'integer'],
        [['title', 'creation_date', 'author.name'], 'safe'],
    ];
}
```
Carsten Brandt committed
434

435 436 437 438 439 440
In `search()` you then just add another filter condition with:

```php
$query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name')]);
```

441 442
> Info: In the above we use the same string for the relation name and the table alias; however, when your alias and relation name
> differ, you have to pay attention to where you use the alias and where you use the relation name.
443
> A simple rule for this is to use the alias in every place that is used to build the database query and the
444
> relation name in all other definitions such as `attributes()` and `rules()` etc.
445
>
446
> For example, if you use the alias `au` for the author relation table, the joinWith statement looks like the following:
447 448 449 450 451 452 453 454 455 456 457 458
>
> ```php
> $query->joinWith(['author' => function($query) { $query->from(['au' => 'users']); }]);
> ```
> It is also possible to just call `$query->joinWith(['author']);` when the alias is defined in the relation definition.
>
> The alias has to be used in the filter condition but the attribute name stays the same:
>
> ```php
> $query->andFilterWhere(['LIKE', 'au.name', $this->getAttribute('author.name')]);
> ```
>
459
> The same is true for the sorting definition:
460
>
461 462 463 464 465 466
> ```php
> $dataProvider->sort->attributes['author.name'] = [
>      'asc' => ['au.name' => SORT_ASC],
>      'desc' => ['au.name' => SORT_DESC],
> ];
> ```
467
>
468
> Also, when specifying the [[yii\data\Sort::defaultOrder|defaultOrder]] for sorting, you need to use the relation name
469 470 471 472 473
> instead of the alias:
>
> ```php
> $dataProvider->sort->defaultOrder = ['author.name' => SORT_ASC];
> ```
474 475

> Info: For more information on `joinWith` and the queries performed in the background, check the
476
> [active record docs on joining with relations](db-active-record.md#joining-with-relations).
Qiang Xue committed
477

478
#### Using SQL views for filtering, sorting and displaying data
Mark committed
479

480 481
There is also another approach that can be faster and more useful - sql views. For example, if we need to show the gridview 
with users and their profiles, we can do so in this way:
482

483
```sql
484 485
CREATE OR REPLACE VIEW vw_user_info AS
    SELECT user.*, user_profile.lastname, user_profile.firstname
Mark committed
486
    FROM user, user_profile
487 488 489
    WHERE user.id = user_profile.user_id
```

490
Then you need to create the ActiveRecord that will be representing this view:
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

```php

namespace app\models\views\grid;

use yii\db\ActiveRecord;

class UserView extends ActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'vw_user_info';
    }

    public static function primaryKey()
    {
        return ['id'];
    }

Mark committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // define here your rules
        ];
    }

    /**
     * @inheritdoc
     */
    public static function attributeLabels()
    {
        return [
            // define here your attribute labels
        ];
    }


535 536 537
}
```

538
After that you can use this UserView active record with search models, without additional specification of sorting and filtering attributes.
539 540
All attributes will be working out of the box. Note that this approach has several pros and cons:

541
- you don't need to specify different sorting and filtering conditions. Everything works out of the box;
542
- it can be much faster because of the data size, count of sql queries performed (for each relation you will not need any additional query);
543 544
- since this is just a simple mapping UI on the sql view it lacks some domain logic that is in your entities, so if you have some methods like `isActive`,
`isDeleted` or others that will influence the UI, you will need to duplicate them in this class too.
545 546


547 548 549
### Multiple GridViews on one page

You can use more than one GridView on a single page but some additional configuration is needed so that
550
they do not interfere with each other.
551
When using multiple instances of GridView you have to configure different parameter names for
552
the generated sort and pagination links so that each GridView has its own individual sorting and pagination.
553
You do so by setting the [[yii\data\Sort::sortParam|sortParam]] and [[yii\data\Pagination::pageParam|pageParam]]
554 555
of the dataProvider's [[yii\data\BaseDataProvider::$sort|sort]] and [[yii\data\BaseDataProvider::$pagination|pagination]]
instances.
556

557
Assume we want to list the `Post` and `User` models for which we have already prepared two data providers
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
in `$userProvider` and `$postProvider`:

```php
use yii\grid\GridView;

$userProvider->pagination->pageParam = 'user-page';
$userProvider->sort->sortParam = 'user-sort';

$postProvider->pagination->pageParam = 'post-page';
$postProvider->sort->sortParam = 'post-sort';

echo '<h1>Users</h1>';
echo GridView::widget([
    'dataProvider' => $userProvider,
]);

echo '<h1>Posts</h1>';
echo GridView::widget([
    'dataProvider' => $postProvider,
]);
```

### Using GridView with Pjax

582
TBD