output-data-widgets.md 11.2 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 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
ListView
--------



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.
 
DetailView uses the [[yii\widgets\DetailView::$attributes]] property to determines which model attributes should be displayed and how they
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
--------
41 42

Data grid or GridView is one of the most powerful Yii widgets. It is extremely useful if you need to quickly build admin
43
section of the system. It takes data from [data provider](data-providers.md) and renders each row using a set of columns
44 45 46 47 48 49 50 51 52
presenting data in a form of a table.

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

Grid view supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode
or 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 are still functioning as expected.

Anderson Müller committed
53
The minimal code needed to use GridView is as follows:
54 55

```php
56
use yii\grid\GridView;
Alexander Makarov committed
57 58 59
use yii\data\ActiveDataProvider;

$dataProvider = new ActiveDataProvider([
60 61 62 63
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
Alexander Makarov committed
64 65
]);
echo GridView::widget([
66
    'dataProvider' => $dataProvider,
Alexander Makarov committed
67
]);
68 69 70 71 72
```

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

Qiang Xue committed
73
### Grid columns
74 75 76 77 78 79

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

These are defined in the columns part of GridView config like the following:

```php
80
echo GridView::widget([
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        // A simple column defined by the data contained in $dataProvider.
        // Data from model's column1 will be used.
        'id',
        'username',
        // More complex one.
        [
            'class' => 'yii\grid\DataColumn', // can be omitted, default
            'value' => function ($data) {
                return $data->name;
            },
        ],
    ],
96
]);
97 98
```

Alexander Makarov committed
99
Note that if columns part of config isn't specified, Yii tries to show all possible data provider model columns.
100 101 102

### Column classes

Alexander Makarov committed
103 104 105 106
Grid columns could be customized by using different column classes:

```php
echo GridView::widget([
107 108 109 110 111 112
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn', // <-- here
            // you may configure additional properties here
        ],
Alexander Makarov committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126
```

Additionally to column classes provided by Yii that we'll review below you can create your own column classes.

Each column class extends from [[\yii\grid\Column]] so there some common options you can set while configuring
grid columns.

- `header` allows to set content for header row.
- `footer` allows to set content for footer row.
- `visible` is the column should be visible.
- `content` allows you to pass a valid PHP callback that will return data for a row. The format is the following:

```php
function ($model, $key, $index, $grid) {
127
    return 'a string';
Alexander Makarov committed
128 129 130 131 132 133 134 135 136
}
```

You may specify various container HTML options passing arrays to:

- `headerOptions`
- `contentOptions`
- `footerOptions`
- `filterOptions`
137 138 139

#### Data column

Alexander Makarov committed
140 141 142 143 144
Data column is for displaying and sorting data. It is default column type so specifying class could be omitted when
using it.

TBD

145 146
#### Action column

Alexander Makarov committed
147 148 149 150
Action column displays action buttons such as update or delete for each row.

```php
echo GridView::widget([
151 152 153 154 155 156
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'class' => 'yii\grid\ActionColumn',
            // you may configure additional properties here
        ],
Alexander Makarov committed
157 158 159 160 161 162 163 164
```

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.
- `template` the template used for composing each cell in the action column. Tokens enclosed within curly brackets are
  treated as controller action IDs (also called *button names* in the context of action column). They will be replaced
165
  by the corresponding button rendering callbacks specified in [[yii\grid\ActionColumn::$buttons|buttons]]. For example, the token `{view}` will be
Alexander Makarov committed
166 167 168 169 170 171 172
  replaced by the result of the callback `buttons['view']`. If a callback cannot be found, the token will be replaced
  with an empty string. Default is `{view} {update} {delete}`.
- `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
function ($url, $model) {
173
    // return the button HTML code
Alexander Makarov committed
174 175 176 177 178 179 180
}
```

In the code above `$url` is the URL that the column creates for the button, and `$model` is the model object being
rendered for the current row.

- `urlCreator` is a callback that creates a button URL using the specified model information. The signature of
MarsuBoss committed
181 182
  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
183

184 185
#### Checkbox column

Alexander Makarov committed
186
CheckboxColumn displays a column of checkboxes.
Qiang Xue committed
187

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

Alexander Makarov committed
190 191
```php
echo GridView::widget([
192 193 194 195 196 197 198 199
    'dataProvider' => $dataProvider,
    'columns' => [
        // ...
        [
            'class' => 'yii\grid\CheckboxColumn',
            // you may configure additional properties here
        ],
    ],
Alexander Makarov committed
200 201 202 203 204 205 206 207 208 209
```

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
```

210 211
#### Serial column

Alexander Makarov committed
212 213 214 215 216 217
Serial column renders row numbers starting with `1` and going forward.

Usage is as simple as the following:

```php
echo GridView::widget([
218 219 220
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'], // <-- here
Alexander Makarov committed
221 222
```

223 224 225 226 227 228 229 230
Sorting data
------------

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

Filtering data
--------------

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
For filtering data the GridView needs a [model](model.md) that takes the input from the filtering
form and adjusts the query of the dataprovider to respect the search criteria.
A common practice when using [active records](active-record.md) is to create a search Model class
that extends from the active record class. This class then defines the validation rules for the search
and provides a `search()` method that will return the data provider.

To add search capability for the `Post` model we can create `PostSearch` like in the following example:

```php
<?php

namespace app\models;

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

class PostSearch extends Post
{
    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]);
        $query->andFilterWhere(['like', 'title', $this->name])
              ->andFilterWhere(['like', 'creation_date', $this->creation_date]);

        return $dataProvider;
    }
}

```

Carsten Brandt committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
You can use this function in the controller to get the dataProvider for the GridView:

```php
$searchModel = new PostSearch();
$dataProvider = $searchModel->search($_GET);

return $this->render('myview', [
	'dataProvider' => $dataProvider,
	'searchModel' => $searchModel,
]);
```

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

```php
echo GridView::widget([
    'dataProvider' => $dataProvider,
	'filterModel' => $searchModel,
]);
```


Working with model relations
312 313
----------------------------

314
When displaying active records in a GridView you might encounter the case where you display values of related
Carsten Brandt committed
315
columns such as the post's author's name instead of just his `id`.
Carsten Brandt committed
316 317 318
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.
319
You have to adjust the `PostSearch` model that has been introduced in the last section to add this functionallity.
Carsten Brandt committed
320

321
To enable sorting on a related column you have to join the related table and add the sorting rule
Carsten Brandt committed
322
to the Sort component of the data provider:
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

```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`
$query->joinWith(['author' => function($query) { $query->from(['author' => 'users']); }]);
// 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
343

344 345 346
```php
public function attributes()
{
Carsten Brandt committed
347 348
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['author.name']);
349 350 351 352 353 354 355 356 357 358
}

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

360
In `search()` you then just add another filter condition with `$query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name')]);`.
361 362 363

> Info: For more information on `joinWith` and the queries performed in the background, check the
> [active record docs on eager and lazy loading](active-record.md#lazy-and-eager-loading).
Qiang Xue committed
364