Issues (910)

framework/grid/GridView.php (2 issues)

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\grid;
9
10
use Closure;
11
use Yii;
12
use yii\base\InvalidConfigException;
13
use yii\base\Model;
14
use yii\helpers\Html;
15
use yii\helpers\Json;
16
use yii\helpers\Url;
17
use yii\i18n\Formatter;
18
use yii\widgets\BaseListView;
19
20
/**
21
 * The GridView widget is used to display data in a grid.
22
 *
23
 * It provides features like [[sorter|sorting]], [[pager|paging]] and also [[filterModel|filtering]] the data.
24
 *
25
 * A basic usage looks like the following:
26
 *
27
 * ```php
28
 * <?= GridView::widget([
29
 *     'dataProvider' => $dataProvider,
30
 *     'columns' => [
31
 *         'id',
32
 *         'name',
33
 *         'created_at:datetime',
34
 *         // ...
35
 *     ],
36
 * ]) ?>
37
 * ```
38
 *
39
 * The columns of the grid table are configured in terms of [[Column]] classes,
40
 * which are configured via [[columns]].
41
 *
42
 * The look and feel of a grid view can be customized using the large amount of properties.
43
 *
44
 * For more details and usage information on GridView, see the [guide article on data widgets](guide:output-data-widgets).
45
 *
46
 * @author Qiang Xue <[email protected]>
47
 * @since 2.0
48
 */
49
class GridView extends BaseListView
50
{
51
    const FILTER_POS_HEADER = 'header';
52
    const FILTER_POS_FOOTER = 'footer';
53
    const FILTER_POS_BODY = 'body';
54
55
    /**
56
     * @var string the default data column class if the class name is not explicitly specified when configuring a data column.
57
     * Defaults to 'yii\grid\DataColumn'.
58
     */
59
    public $dataColumnClass;
60
    /**
61
     * @var string the caption of the grid table
62
     * @see captionOptions
63
     */
64
    public $caption;
65
    /**
66
     * @var array the HTML attributes for the caption element.
67
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
68
     * @see caption
69
     */
70
    public $captionOptions = [];
71
    /**
72
     * @var array the HTML attributes for the grid table element.
73
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
74
     */
75
    public $tableOptions = ['class' => 'table table-striped table-bordered'];
76
    /**
77
     * @var array the HTML attributes for the container tag of the grid view.
78
     * The "tag" element specifies the tag name of the container element and defaults to "div".
79
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
80
     */
81
    public $options = ['class' => 'grid-view'];
82
    /**
83
     * @var array the HTML attributes for the table header row.
84
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
85
     */
86
    public $headerRowOptions = [];
87
    /**
88
     * @var array the HTML attributes for the table footer row.
89
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
90
     */
91
    public $footerRowOptions = [];
92
    /**
93
     * @var array|Closure the HTML attributes for the table body rows. This can be either an array
94
     * specifying the common HTML attributes for all body rows, or an anonymous function that
95
     * returns an array of the HTML attributes. The anonymous function will be called once for every
96
     * data model returned by [[dataProvider]]. It should have the following signature:
97
     *
98
     * ```php
99
     * function ($model, $key, $index, $grid)
100
     * ```
101
     *
102
     * - `$model`: the current data model being rendered
103
     * - `$key`: the key value associated with the current data model
104
     * - `$index`: the zero-based index of the data model in the model array returned by [[dataProvider]]
105
     * - `$grid`: the GridView object
106
     *
107
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
108
     */
109
    public $rowOptions = [];
110
    /**
111
     * @var Closure an anonymous function that is called once BEFORE rendering each data model.
112
     * It should have the similar signature as [[rowOptions]]. The return result of the function
113
     * will be rendered directly.
114
     */
115
    public $beforeRow;
116
    /**
117
     * @var Closure an anonymous function that is called once AFTER rendering each data model.
118
     * It should have the similar signature as [[rowOptions]]. The return result of the function
119
     * will be rendered directly.
120
     */
121
    public $afterRow;
122
    /**
123
     * @var bool whether to show the header section of the grid table.
124
     */
125
    public $showHeader = true;
126
    /**
127
     * @var bool whether to show the footer section of the grid table.
128
     */
129
    public $showFooter = false;
130
    /**
131
     * @var bool whether to place footer after body in DOM if $showFooter is true
132
     * @since 2.0.14
133
     */
134
    public $placeFooterAfterBody = false;
135
    /**
136
     * @var bool whether to show the grid view if [[dataProvider]] returns no data.
137
     */
138
    public $showOnEmpty = true;
139
    /**
140
     * @var array|Formatter|null the formatter used to format model attribute values into displayable texts.
141
     * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
142
     * instance. If this property is not set, the "formatter" application component will be used.
143
     */
144
    public $formatter;
145
    /**
146
     * @var array grid column configuration. Each array element represents the configuration
147
     * for one particular grid column. For example,
148
     *
149
     * ```php
150
     * [
151
     *     ['class' => SerialColumn::class],
152
     *     [
153
     *         'class' => DataColumn::class, // this line is optional
154
     *         'attribute' => 'name',
155
     *         'format' => 'text',
156
     *         'label' => 'Name',
157
     *     ],
158
     *     ['class' => CheckboxColumn::class],
159
     * ]
160
     * ```
161
     *
162
     * If a column is of class [[DataColumn]], the "class" element can be omitted.
163
     *
164
     * As a shortcut format, a string may be used to specify the configuration of a data column
165
     * which only contains [[DataColumn::attribute|attribute]], [[DataColumn::format|format]],
166
     * and/or [[DataColumn::label|label]] options: `"attribute:format:label"`.
167
     * For example, the above "name" column can also be specified as: `"name:text:Name"`.
168
     * Both "format" and "label" are optional. They will take default values if absent.
169
     *
170
     * Using the shortcut format the configuration for columns in simple cases would look like this:
171
     *
172
     * ```php
173
     * [
174
     *     'id',
175
     *     'amount:currency:Total Amount',
176
     *     'created_at:datetime',
177
     * ]
178
     * ```
179
     *
180
     * When using a [[dataProvider]] with active records, you can also display values from related records,
181
     * e.g. the `name` attribute of the `author` relation:
182
     *
183
     * ```php
184
     * // shortcut syntax
185
     * 'author.name',
186
     * // full syntax
187
     * [
188
     *     'attribute' => 'author.name',
189
     *     // ...
190
     * ]
191
     * ```
192
     */
193
    public $columns = [];
194
    /**
195
     * @var string the HTML display when the content of a cell is empty.
196
     * This property is used to render cells that have no defined content,
197
     * e.g. empty footer or filter cells.
198
     *
199
     * Note that this is not used by the [[DataColumn]] if a data item is `null`. In that case
200
     * the [[\yii\i18n\Formatter::nullDisplay|nullDisplay]] property of the [[formatter]] will
201
     * be used to indicate an empty data value.
202
     */
203
    public $emptyCell = '&nbsp;';
204
    /**
205
     * @var \yii\base\Model|null the model that keeps the user-entered filter data. When this property is set,
206
     * the grid view will enable column-based filtering. Each data column by default will display a text field
207
     * at the top that users can fill in to filter the data.
208
     *
209
     * Note that in order to show an input field for filtering, a column must have its [[DataColumn::attribute]]
210
     * property set and the attribute should be active in the current scenario of $filterModel or have
211
     * [[DataColumn::filter]] set as the HTML code for the input field.
212
     *
213
     * When this property is not set (null) the filtering feature is disabled.
214
     */
215
    public $filterModel;
216
    /**
217
     * @var string|array|null the URL for returning the filtering result. [[Url::to()]] will be called to
218
     * normalize the URL. If not set, the current controller action will be used.
219
     * When the user makes change to any filter input, the current filtering inputs will be appended
220
     * as GET parameters to this URL.
221
     */
222
    public $filterUrl;
223
    /**
224
     * @var string additional jQuery selector for selecting filter input fields
225
     */
226
    public $filterSelector;
227
    /**
228
     * @var string whether the filters should be displayed in the grid view. Valid values include:
229
     *
230
     * - [[FILTER_POS_HEADER]]: the filters will be displayed on top of each column's header cell.
231
     * - [[FILTER_POS_BODY]]: the filters will be displayed right below each column's header cell.
232
     * - [[FILTER_POS_FOOTER]]: the filters will be displayed below each column's footer cell.
233
     */
234
    public $filterPosition = self::FILTER_POS_BODY;
235
    /**
236
     * @var array the HTML attributes for the filter row element.
237
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
238
     */
239
    public $filterRowOptions = ['class' => 'filters'];
240
    /**
241
     * @var array the options for rendering the filter error summary.
242
     * Please refer to [[Html::errorSummary()]] for more details about how to specify the options.
243
     * @see renderErrors()
244
     */
245
    public $filterErrorSummaryOptions = ['class' => 'error-summary'];
246
    /**
247
     * @var array the options for rendering every filter error message.
248
     * This is mainly used by [[Html::error()]] when rendering an error message next to every filter input field.
249
     */
250
    public $filterErrorOptions = ['class' => 'help-block'];
251
    /**
252
     * @var bool whatever to apply filters on losing focus. Leaves an ability to manage filters via yiiGridView JS
253
     * @since 2.0.16
254
     */
255
    public $filterOnFocusOut = true;
256
    /**
257
     * @var string the layout that determines how different sections of the grid view should be organized.
258
     * The following tokens will be replaced with the corresponding section contents:
259
     *
260
     * - `{summary}`: the summary section. See [[renderSummary()]].
261
     * - `{errors}`: the filter model error summary. See [[renderErrors()]].
262
     * - `{items}`: the list items. See [[renderItems()]].
263
     * - `{sorter}`: the sorter. See [[renderSorter()]].
264
     * - `{pager}`: the pager. See [[renderPager()]].
265
     */
266
    public $layout = "{summary}\n{items}\n{pager}";
267
268
269
    /**
270
     * Initializes the grid view.
271
     * This method will initialize required property values and instantiate [[columns]] objects.
272
     */
273 17
    public function init()
274
    {
275 17
        parent::init();
276 17
        if ($this->formatter === null) {
277 17
            $this->formatter = Yii::$app->getFormatter();
278
        } elseif (is_array($this->formatter)) {
279
            $this->formatter = Yii::createObject($this->formatter);
280
        }
281 17
        if (!$this->formatter instanceof Formatter) {
282
            throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
283
        }
284 17
        if (!isset($this->filterRowOptions['id'])) {
285 17
            $this->filterRowOptions['id'] = $this->options['id'] . '-filters';
286
        }
287
288 17
        $this->initColumns();
289
    }
290
291
    /**
292
     * Runs the widget.
293
     */
294 5
    public function run()
295
    {
296 5
        $view = $this->getView();
297 5
        GridViewAsset::register($view);
298 5
        $id = $this->options['id'];
299 5
        $options = Json::htmlEncode(array_merge($this->getClientOptions(), ['filterOnFocusOut' => $this->filterOnFocusOut]));
300 5
        $view->registerJs("jQuery('#$id').yiiGridView($options);");
301 5
        parent::run();
302
    }
303
304
    /**
305
     * Renders validator errors of filter model.
306
     * @return string the rendering result.
307
     */
308
    public function renderErrors()
309
    {
310
        if ($this->filterModel instanceof Model && $this->filterModel->hasErrors()) {
311
            return Html::errorSummary($this->filterModel, $this->filterErrorSummaryOptions);
312
        }
313
314
        return '';
315
    }
316
317
    /**
318
     * {@inheritdoc}
319
     */
320 5
    public function renderSection($name)
321
    {
322
        switch ($name) {
323 5
            case '{errors}':
324
                return $this->renderErrors();
325
            default:
326 5
                return parent::renderSection($name);
327
        }
328
    }
329
330
    /**
331
     * Returns the options for the grid view JS widget.
332
     * @return array the options
333
     */
334 5
    protected function getClientOptions()
335
    {
336 5
        $filterUrl = isset($this->filterUrl) ? $this->filterUrl : Yii::$app->request->url;
337 5
        $id = $this->filterRowOptions['id'];
338 5
        $filterSelector = "#$id input, #$id select";
339 5
        if (isset($this->filterSelector)) {
340
            $filterSelector .= ', ' . $this->filterSelector;
341
        }
342
343 5
        return [
344 5
            'filterUrl' => Url::to($filterUrl),
345 5
            'filterSelector' => $filterSelector,
346 5
        ];
347
    }
348
349
    /**
350
     * Renders the data models for the grid view.
351
     * @return string the HTML code of table
352
     */
353 5
    public function renderItems()
354
    {
355 5
        $caption = $this->renderCaption();
356 5
        $columnGroup = $this->renderColumnGroup();
357 5
        $tableHeader = $this->showHeader ? $this->renderTableHeader() : false;
358 5
        $tableBody = $this->renderTableBody();
359
360 5
        $tableFooter = false;
361 5
        $tableFooterAfterBody = false;
362
363 5
        if ($this->showFooter) {
364 1
            if ($this->placeFooterAfterBody) {
365 1
                $tableFooterAfterBody = $this->renderTableFooter();
366
            } else {
367 1
                $tableFooter = $this->renderTableFooter();
368
            }
369
        }
370
371 5
        $content = array_filter([
372 5
            $caption,
373 5
            $columnGroup,
374 5
            $tableHeader,
375 5
            $tableFooter,
376 5
            $tableBody,
377 5
            $tableFooterAfterBody,
378 5
        ]);
379
380 5
        return Html::tag('table', implode("\n", $content), $this->tableOptions);
381
    }
382
383
    /**
384
     * Renders the caption element.
385
     * @return bool|string the rendered caption element or `false` if no caption element should be rendered.
386
     */
387 5
    public function renderCaption()
388
    {
389 5
        if (!empty($this->caption)) {
390
            return Html::tag('caption', $this->caption, $this->captionOptions);
391
        }
392
393 5
        return false;
394
    }
395
396
    /**
397
     * Renders the column group HTML.
398
     * @return bool|string the column group HTML or `false` if no column group should be rendered.
399
     */
400 5
    public function renderColumnGroup()
401
    {
402 5
        foreach ($this->columns as $column) {
403
            /* @var $column Column */
404 1
            if (!empty($column->options)) {
405
                $cols = [];
406
                foreach ($this->columns as $col) {
407
                    $cols[] = Html::tag('col', '', $col->options);
408
                }
409
410
                return Html::tag('colgroup', implode("\n", $cols));
411
            }
412
        }
413
414 5
        return false;
415
    }
416
417
    /**
418
     * Renders the table header.
419
     * @return string the rendering result.
420
     */
421 2
    public function renderTableHeader()
422
    {
423 2
        $cells = [];
424 2
        foreach ($this->columns as $column) {
425
            /* @var $column Column */
426 2
            $cells[] = $column->renderHeaderCell();
427
        }
428 2
        $content = Html::tag('tr', implode('', $cells), $this->headerRowOptions);
429 2
        if ($this->filterPosition === self::FILTER_POS_HEADER) {
430
            $content = $this->renderFilters() . $content;
431 2
        } elseif ($this->filterPosition === self::FILTER_POS_BODY) {
432 2
            $content .= $this->renderFilters();
433
        }
434
435 2
        return "<thead>\n" . $content . "\n</thead>";
436
    }
437
438
    /**
439
     * Renders the table footer.
440
     * @return string the rendering result.
441
     */
442 1
    public function renderTableFooter()
443
    {
444 1
        $cells = [];
445 1
        foreach ($this->columns as $column) {
446
            /* @var $column Column */
447
            $cells[] = $column->renderFooterCell();
448
        }
449 1
        $content = Html::tag('tr', implode('', $cells), $this->footerRowOptions);
450 1
        if ($this->filterPosition === self::FILTER_POS_FOOTER) {
451
            $content .= $this->renderFilters();
452
        }
453
454 1
        return "<tfoot>\n" . $content . "\n</tfoot>";
455
    }
456
457
    /**
458
     * Renders the filter.
459
     * @return string the rendering result.
460
     */
461 2
    public function renderFilters()
462
    {
463 2
        if ($this->filterModel !== null) {
464
            $cells = [];
465
            foreach ($this->columns as $column) {
466
                /* @var $column Column */
467
                $cells[] = $column->renderFilterCell();
468
            }
469
470
            return Html::tag('tr', implode('', $cells), $this->filterRowOptions);
471
        }
472
473 2
        return '';
474
    }
475
476
    /**
477
     * Renders the table body.
478
     * @return string the rendering result.
479
     */
480 5
    public function renderTableBody()
481
    {
482 5
        $models = array_values($this->dataProvider->getModels());
483 5
        $keys = $this->dataProvider->getKeys();
484 5
        $rows = [];
485 5
        foreach ($models as $index => $model) {
486 1
            $key = $keys[$index];
487 1
            if ($this->beforeRow !== null) {
488
                $row = call_user_func($this->beforeRow, $model, $key, $index, $this);
489
                if (!empty($row)) {
490
                    $rows[] = $row;
491
                }
492
            }
493
494 1
            $rows[] = $this->renderTableRow($model, $key, $index);
495
496 1
            if ($this->afterRow !== null) {
497
                $row = call_user_func($this->afterRow, $model, $key, $index, $this);
498
                if (!empty($row)) {
499
                    $rows[] = $row;
500
                }
501
            }
502
        }
503
504 5
        if (empty($rows) && $this->emptyText !== false) {
505 3
            $colspan = count($this->columns);
506
507 3
            return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
508
        }
509
510 2
        return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
511
    }
512
513
    /**
514
     * Renders a table row with the given data model and key.
515
     * @param mixed $model the data model to be rendered
516
     * @param mixed $key the key associated with the data model
517
     * @param int $index the zero-based index of the data model among the model array returned by [[dataProvider]].
518
     * @return string the rendering result
519
     */
520 1
    public function renderTableRow($model, $key, $index)
521
    {
522 1
        $cells = [];
523
        /* @var $column Column */
524 1
        foreach ($this->columns as $column) {
525 1
            $cells[] = $column->renderDataCell($model, $key, $index);
526
        }
527 1
        if ($this->rowOptions instanceof Closure) {
528
            $options = call_user_func($this->rowOptions, $model, $key, $index, $this);
529
        } else {
530 1
            $options = $this->rowOptions;
531
        }
532 1
        $options['data-key'] = is_array($key) ? json_encode($key) : (string) $key;
533
534 1
        return Html::tag('tr', implode('', $cells), $options);
535
    }
536
537
    /**
538
     * Creates column objects and initializes them.
539
     */
540 17
    protected function initColumns()
541
    {
542 17
        if (empty($this->columns)) {
543 8
            $this->guessColumns();
544
        }
545 17
        foreach ($this->columns as $i => $column) {
546 10
            if (is_string($column)) {
547 5
                $column = $this->createDataColumn($column);
548
            } else {
549 5
                $column = Yii::createObject(array_merge([
550 5
                    'class' => $this->dataColumnClass ?: DataColumn::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

550
                    'class' => $this->dataColumnClass ?: /** @scrutinizer ignore-deprecated */ DataColumn::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
551 5
                    'grid' => $this,
552 5
                ], $column));
553
            }
554 10
            if (!$column->visible) {
555
                unset($this->columns[$i]);
556
                continue;
557
            }
558 10
            $this->columns[$i] = $column;
559
        }
560
    }
561
562
    /**
563
     * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label".
564
     * @param string $text the column specification string
565
     * @return DataColumn the column instance
566
     * @throws InvalidConfigException if the column specification is invalid
567
     */
568 5
    protected function createDataColumn($text)
569
    {
570 5
        if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
571
            throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
572
        }
573
574 5
        return Yii::createObject([
575 5
            'class' => $this->dataColumnClass ?: DataColumn::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

575
            'class' => $this->dataColumnClass ?: /** @scrutinizer ignore-deprecated */ DataColumn::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
576 5
            'grid' => $this,
577 5
            'attribute' => $matches[1],
578 5
            'format' => isset($matches[3]) ? $matches[3] : 'text',
579 5
            'label' => isset($matches[5]) ? $matches[5] : null,
580 5
        ]);
581
    }
582
583
    /**
584
     * This function tries to guess the columns to show from the given data
585
     * if [[columns]] are not explicitly specified.
586
     */
587 8
    protected function guessColumns()
588
    {
589 8
        $models = $this->dataProvider->getModels();
590 8
        $model = reset($models);
591 8
        if (is_array($model) || is_object($model)) {
592 1
            foreach ($model as $name => $value) {
593 1
                if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) {
594 1
                    $this->columns[] = (string) $name;
595
                }
596
            }
597
        }
598
    }
599
}
600