GridView.php 13 KB

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