GridView.php 20 KB

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