Completed
Pull Request — 2.1 (#11477)
by Angel
08:46
created

GridView::renderSection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

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