You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

577 lines
20KB

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