GridView.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 string the layout that determines how different sections of the grid view should be organized.
  249. * The following tokens will be replaced with the corresponding section contents:
  250. *
  251. * - `{summary}`: the summary section. See [[renderSummary()]].
  252. * - `{errors}`: the filter model error summary. See [[renderErrors()]].
  253. * - `{items}`: the list items. See [[renderItems()]].
  254. * - `{sorter}`: the sorter. See [[renderSorter()]].
  255. * - `{pager}`: the pager. See [[renderPager()]].
  256. */
  257. public $layout = "{summary}\n{items}\n{pager}";
  258. /**
  259. * Initializes the grid view.
  260. * This method will initialize required property values and instantiate [[columns]] objects.
  261. */
  262. public function init()
  263. {
  264. parent::init();
  265. if ($this->formatter === null) {
  266. $this->formatter = Yii::$app->getFormatter();
  267. } elseif (is_array($this->formatter)) {
  268. $this->formatter = Yii::createObject($this->formatter);
  269. }
  270. if (!$this->formatter instanceof Formatter) {
  271. throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
  272. }
  273. if (!isset($this->filterRowOptions['id'])) {
  274. $this->filterRowOptions['id'] = $this->options['id'] . '-filters';
  275. }
  276. $this->initColumns();
  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. * Renders validator errors of filter model.
  292. * @return string the rendering result.
  293. */
  294. public function renderErrors()
  295. {
  296. if ($this->filterModel instanceof Model && $this->filterModel->hasErrors()) {
  297. return Html::errorSummary($this->filterModel, $this->filterErrorSummaryOptions);
  298. }
  299. return '';
  300. }
  301. /**
  302. * {@inheritdoc}
  303. */
  304. public function renderSection($name)
  305. {
  306. switch ($name) {
  307. case '{errors}':
  308. return $this->renderErrors();
  309. default:
  310. return parent::renderSection($name);
  311. }
  312. }
  313. /**
  314. * Returns the options for the grid view JS widget.
  315. * @return array the options
  316. */
  317. protected function getClientOptions()
  318. {
  319. $filterUrl = isset($this->filterUrl) ? $this->filterUrl : Yii::$app->request->url;
  320. $id = $this->filterRowOptions['id'];
  321. $filterSelector = "#$id input, #$id select";
  322. if (isset($this->filterSelector)) {
  323. $filterSelector .= ', ' . $this->filterSelector;
  324. }
  325. return [
  326. 'filterUrl' => Url::to($filterUrl),
  327. 'filterSelector' => $filterSelector,
  328. ];
  329. }
  330. /**
  331. * Renders the data models for the grid view.
  332. * @return string the HTML code of table
  333. */
  334. public function renderItems()
  335. {
  336. $caption = $this->renderCaption();
  337. $columnGroup = $this->renderColumnGroup();
  338. $tableHeader = $this->showHeader ? $this->renderTableHeader() : false;
  339. $tableBody = $this->renderTableBody();
  340. $tableFooter = false;
  341. $tableFooterAfterBody = false;
  342. if ($this->showFooter) {
  343. if ($this->placeFooterAfterBody) {
  344. $tableFooterAfterBody = $this->renderTableFooter();
  345. } else {
  346. $tableFooter = $this->renderTableFooter();
  347. }
  348. }
  349. $content = array_filter([
  350. $caption,
  351. $columnGroup,
  352. $tableHeader,
  353. $tableFooter,
  354. $tableBody,
  355. $tableFooterAfterBody,
  356. ]);
  357. return Html::tag('table', implode("\n", $content), $this->tableOptions);
  358. }
  359. /**
  360. * Renders the caption element.
  361. * @return bool|string the rendered caption element or `false` if no caption element should be rendered.
  362. */
  363. public function renderCaption()
  364. {
  365. if (!empty($this->caption)) {
  366. return Html::tag('caption', $this->caption, $this->captionOptions);
  367. }
  368. return false;
  369. }
  370. /**
  371. * Renders the column group HTML.
  372. * @return bool|string the column group HTML or `false` if no column group should be rendered.
  373. */
  374. public function renderColumnGroup()
  375. {
  376. foreach ($this->columns as $column) {
  377. /* @var $column Column */
  378. if (!empty($column->options)) {
  379. $cols = [];
  380. foreach ($this->columns as $col) {
  381. $cols[] = Html::tag('col', '', $col->options);
  382. }
  383. return Html::tag('colgroup', implode("\n", $cols));
  384. }
  385. }
  386. return false;
  387. }
  388. /**
  389. * Renders the table header.
  390. * @return string the rendering result.
  391. */
  392. public function renderTableHeader()
  393. {
  394. $cells = [];
  395. foreach ($this->columns as $column) {
  396. /* @var $column Column */
  397. $cells[] = $column->renderHeaderCell();
  398. }
  399. $content = Html::tag('tr', implode('', $cells), $this->headerRowOptions);
  400. if ($this->filterPosition === self::FILTER_POS_HEADER) {
  401. $content = $this->renderFilters() . $content;
  402. } elseif ($this->filterPosition === self::FILTER_POS_BODY) {
  403. $content .= $this->renderFilters();
  404. }
  405. return "<thead>\n" . $content . "\n</thead>";
  406. }
  407. /**
  408. * Renders the table footer.
  409. * @return string the rendering result.
  410. */
  411. public function renderTableFooter()
  412. {
  413. $cells = [];
  414. foreach ($this->columns as $column) {
  415. /* @var $column Column */
  416. $cells[] = $column->renderFooterCell();
  417. }
  418. $content = Html::tag('tr', implode('', $cells), $this->footerRowOptions);
  419. if ($this->filterPosition === self::FILTER_POS_FOOTER) {
  420. $content .= $this->renderFilters();
  421. }
  422. return "<tfoot>\n" . $content . "\n</tfoot>";
  423. }
  424. /**
  425. * Renders the filter.
  426. * @return string the rendering result.
  427. */
  428. public function renderFilters()
  429. {
  430. if ($this->filterModel !== null) {
  431. $cells = [];
  432. foreach ($this->columns as $column) {
  433. /* @var $column Column */
  434. $cells[] = $column->renderFilterCell();
  435. }
  436. return Html::tag('tr', implode('', $cells), $this->filterRowOptions);
  437. }
  438. return '';
  439. }
  440. /**
  441. * Renders the table body.
  442. * @return string the rendering result.
  443. */
  444. public function renderTableBody()
  445. {
  446. $models = array_values($this->dataProvider->getModels());
  447. $keys = $this->dataProvider->getKeys();
  448. $rows = [];
  449. foreach ($models as $index => $model) {
  450. $key = $keys[$index];
  451. if ($this->beforeRow !== null) {
  452. $row = call_user_func($this->beforeRow, $model, $key, $index, $this);
  453. if (!empty($row)) {
  454. $rows[] = $row;
  455. }
  456. }
  457. $rows[] = $this->renderTableRow($model, $key, $index);
  458. if ($this->afterRow !== null) {
  459. $row = call_user_func($this->afterRow, $model, $key, $index, $this);
  460. if (!empty($row)) {
  461. $rows[] = $row;
  462. }
  463. }
  464. }
  465. if (empty($rows) && $this->emptyText !== false) {
  466. $colspan = count($this->columns);
  467. return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
  468. }
  469. return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
  470. }
  471. /**
  472. * Renders a table row with the given data model and key.
  473. * @param mixed $model the data model to be rendered
  474. * @param mixed $key the key associated with the data model
  475. * @param int $index the zero-based index of the data model among the model array returned by [[dataProvider]].
  476. * @return string the rendering result
  477. */
  478. public function renderTableRow($model, $key, $index)
  479. {
  480. $cells = [];
  481. /* @var $column Column */
  482. foreach ($this->columns as $column) {
  483. $cells[] = $column->renderDataCell($model, $key, $index);
  484. }
  485. if ($this->rowOptions instanceof Closure) {
  486. $options = call_user_func($this->rowOptions, $model, $key, $index, $this);
  487. } else {
  488. $options = $this->rowOptions;
  489. }
  490. $options['data-key'] = is_array($key) ? json_encode($key) : (string) $key;
  491. return Html::tag('tr', implode('', $cells), $options);
  492. }
  493. /**
  494. * Creates column objects and initializes them.
  495. */
  496. protected function initColumns()
  497. {
  498. if (empty($this->columns)) {
  499. $this->guessColumns();
  500. }
  501. foreach ($this->columns as $i => $column) {
  502. if (is_string($column)) {
  503. $column = $this->createDataColumn($column);
  504. } else {
  505. $column = Yii::createObject(array_merge([
  506. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  507. 'grid' => $this,
  508. ], $column));
  509. }
  510. if (!$column->visible) {
  511. unset($this->columns[$i]);
  512. continue;
  513. }
  514. $this->columns[$i] = $column;
  515. }
  516. }
  517. /**
  518. * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label".
  519. * @param string $text the column specification string
  520. * @return DataColumn the column instance
  521. * @throws InvalidConfigException if the column specification is invalid
  522. */
  523. protected function createDataColumn($text)
  524. {
  525. if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
  526. throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  527. }
  528. return Yii::createObject([
  529. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  530. 'grid' => $this,
  531. 'attribute' => $matches[1],
  532. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  533. 'label' => isset($matches[5]) ? $matches[5] : null,
  534. ]);
  535. }
  536. /**
  537. * This function tries to guess the columns to show from the given data
  538. * if [[columns]] are not explicitly specified.
  539. */
  540. protected function guessColumns()
  541. {
  542. $models = $this->dataProvider->getModels();
  543. $model = reset($models);
  544. if (is_array($model) || is_object($model)) {
  545. foreach ($model as $name => $value) {
  546. if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) {
  547. $this->columns[] = (string) $name;
  548. }
  549. }
  550. }
  551. }
  552. }