Completed
Push — 2.1 ( 21da0e...a39d12 )
by
unknown
10:45
created

GridView::renderCaption()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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