Completed
Push — fix-numbervalidator-comma-deci... ( 08054b...a7f0a3 )
by Alexander
40:41 queued 37:41
created

GridView::createDataColumn()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

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