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.

528 lines
18KB

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