GridView.php 21 KB

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