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.

699 lines
21 KiB

  1. <?php
  2. /*
  3. * The MIT License
  4. *
  5. * Copyright 2019 Blobt.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. namespace iron\grid;
  26. use Closure;
  27. use Yii;
  28. use yii\base\InvalidConfigException;
  29. use yii\base\Model;
  30. use yii\helpers\Html;
  31. use yii\helpers\Json;
  32. use yii\helpers\Url;
  33. use yii\helpers\ArrayHelper;
  34. use yii\i18n\Formatter;
  35. use yii\widgets\BaseListView;
  36. use iron\web\GridViewAsset;
  37. use blobt\grid\DataColumn;
  38. /**
  39. * @author Blobt
  40. * @email 380255922@qq.com
  41. * @created Aug 13, 2019
  42. */
  43. class GridView extends BaseListView
  44. {
  45. /**
  46. * @var string 渲染列数据的类,默认是'yii\grid\DataColumn'
  47. */
  48. public $dataColumnClass;
  49. /**
  50. * @var array 表格说明的html属性
  51. */
  52. public $captionOptions = [];
  53. /**
  54. * @var array 表格外层div的属性
  55. */
  56. public $options = ['class' => 'card'];
  57. /**
  58. * @var array table的html属性
  59. */
  60. public $tableOptions = ['class' => 'table table-bordered table-striped dataTable'];
  61. /**
  62. * @var array 表格头部html属性
  63. */
  64. public $headerRowOptions = [];
  65. /**
  66. * @var array 表格脚部html属性
  67. */
  68. public $footerRowOptions = [];
  69. /**
  70. * @var array|Cloure 表格每一行的html属性
  71. * 这个参数除了可以是一个options数组外,还可以是一个匿名函数,该函数必须返回一个options数组,
  72. * 渲染每一行都会调用该函数
  73. * 该函数必须遵循以下声明规则
  74. * ```php
  75. * function ($model, $key, $index, $grid)
  76. * ```
  77. *
  78. * - `$model`: 每行的模型
  79. * - `$key`: id值
  80. * - `$index`: [[dataProvider]]提供的索引号
  81. * - `$grid`: GridView 对象
  82. */
  83. public $rowOptions = [];
  84. /**
  85. * @var Closure an 一个匿名函数(结构和[[rowOptions]]一样),每行渲染前后都会被调用
  86. */
  87. public $beforeRow;
  88. public $afterRow;
  89. /**
  90. * @var bool 是否显示表格头
  91. */
  92. public $showHeader = true;
  93. /**
  94. * @var bool 是否显示表格脚
  95. */
  96. public $showFooter = false;
  97. /**
  98. * @var bool 没有数据情况下是否显示
  99. */
  100. public $showOnEmpty = true;
  101. /**
  102. * @var array|Formatter 用来格式化输出属性值
  103. */
  104. public $formatter;
  105. /**
  106. * @var string 摘要的显示样式
  107. *
  108. *
  109. * - `{begin}`: 开始条数
  110. * - `{end}`: 结束条数
  111. * - `{count}`: 显示条数
  112. * - `{totalCount}`: 总记录条数
  113. * - `{page}`: 显示分页
  114. * - `{pageCount}`: 总分页数
  115. * - `{select}`: 显示页数
  116. */
  117. public $summary = "{select} 显示{begin}~{end}条 共{totalCount}条";
  118. /**
  119. * @var array 摘要的html属性
  120. */
  121. public $summaryOptions = ['class' => 'summary'];
  122. /**
  123. * @var array 列配置数组. 数组每一项代表一个列,列数组可以包括class、attribute、format、label等。
  124. * 例子:
  125. * ```php
  126. * [
  127. * ['class' => SerialColumn::className()],
  128. * [
  129. * 'class' => DataColumn::className(), //渲染用到的类,没一列都默认使用[[DataColumn]]渲染,所以这里可以忽略
  130. * 'attribute' => 'name', //代表每一行的数据原
  131. * 'format' => 'text', //输出的格式
  132. * 'label' => 'Name', //label
  133. * '' => ''
  134. * ],
  135. * ['class' => CheckboxColumn::className()],
  136. * ]
  137. * ```
  138. *
  139. * 当然,也支持简写成这样:[[DataColumn::attribute|attribute]], [[DataColumn::format|format]],
  140. * [[DataColumn::label|label]] options: `"attribute:format:label"`.
  141. * 所以上面例子的 "name" 列能简写成这样 : `"name:text:Name"`.
  142. * 甚至"format""label"都是可以不制定的,因为它们都有默认值。
  143. *
  144. * 其实大多数情况下都可以使用简写:
  145. *
  146. * ```php
  147. * [
  148. * 'id',
  149. * 'amount:currency:Total Amount',
  150. * 'created_at:datetime',
  151. * ]
  152. * ```
  153. *
  154. * [[dataProvider]]提供active records, 且active record又和其它 active record建立了关联关系的,
  155. * 例如 the `name` 属性是 `author` 关联,那么你可以这样制定数据:
  156. *
  157. * ```php
  158. * // shortcut syntax
  159. * 'author.name',
  160. * // full syntax
  161. * [
  162. * 'attribute' => 'author.name',
  163. * // ...
  164. * ]
  165. * ```
  166. */
  167. public $columns = [];
  168. /**
  169. * @var string 当单元格数据为空时候显示的内容。
  170. */
  171. public $emptyCell = '&nbsp;';
  172. /**
  173. * @var string TODO:这个目前用来做页数选择,具体原理没有研究清楚
  174. */
  175. public $filterSelector = 'select[name="per-page"]';
  176. /**
  177. * @var type
  178. */
  179. public $filter;
  180. /**
  181. * @var array 批量操作的选项
  182. */
  183. public $batch;
  184. /**
  185. * @var string 表格的layout:
  186. *
  187. * - `{summary}`: 摘要.
  188. * - `{items}`: 表格项.
  189. * - `{pager}`: 分页.
  190. * - `{batch}`: 批量处理
  191. */
  192. public $layout = <<< HTML
  193. <div class="card-body">
  194. <div id="example2_wrapper" class="dataTables_wrapper dt-bootstrap4">
  195. <div class="row">
  196. <div class="col-sm-12 col-md-6">
  197. {batch}
  198. <a href="{url}/create" class="btn btn-default"><i class="fas fa-plus-square mr-2"></i>添加</a>
  199. <!-- <a href="#" data-url='export' class="export btn btn-default"><i class="fa fa-file-excel-o"></i>导出</a>-->
  200. <div class="btn-group">
  201. <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fas fa-file-upload mr-2"></i>导出</button>
  202. <ul class="dropdown-menu" role="menu">
  203. <li> <a class="dropdown-item export-page" href="#" data-url="{url}/export">本页</a></li>
  204. <li> <a class="dropdown-item export-all" href="#" data-url="{url}/export">全部</a></li>
  205. </ul>
  206. </div>
  207. <!-- <button type="button" id="export" class="btn btn-default"><i class="fa fa-file-excel-o"></i>导出</button>-->
  208. </div>
  209. <div class="col-sm-12 col-md-6">
  210. {filter}
  211. </div>
  212. </div>
  213. <div class="row">
  214. <div class="col-sm-12">
  215. {items}
  216. </div>
  217. </div>
  218. <div class="row">
  219. <div class="col-sm-12 col-md-5">
  220. <div class="dataTables_length" id="example2_info" role="status" aria-live="polite">
  221. {summary}
  222. </div>
  223. </div>
  224. <div class="col-sm-12 col-md-7">
  225. <div class="dataTables_paginate paging_simple_numbers">
  226. {pager}
  227. </div>
  228. </div>
  229. </div>
  230. </div>
  231. </div>
  232. HTML;
  233. public $batchTemplate = <<< HTML
  234. <div class="btn-group">
  235. <button type="button" class="btn btn-default btn checkbox-toggle"><i class="far fa-square"></i></button>
  236. <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">批量操作</button>
  237. <ul class="dropdown-menu" role="menu">
  238. {items}
  239. </ul>
  240. </div>
  241. HTML;
  242. /**
  243. * 初始化 grid view.
  244. * 初始化必须的属性和每个列对象
  245. * @return
  246. */
  247. public function init()
  248. {
  249. parent::init();
  250. if ($this->formatter === null) {
  251. $this->formatter = Yii::$app->getFormatter();
  252. } elseif (is_array($this->formatter)) {
  253. $this->formatter = Yii::createObject($this->formatter);
  254. }
  255. if (!$this->formatter instanceof Formatter) {
  256. throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
  257. }
  258. $this->pager = [
  259. 'options' => ['class' => ['justify-content-end', 'pagination']],
  260. 'linkOptions' => ['class' => 'page-link'],
  261. 'pageCssClass' => 'paginate_button page-item',
  262. 'disabledPageCssClass' => 'page-link disabled',
  263. 'firstPageLabel' => '&laquo;',
  264. 'prevPageLabel' => '&lsaquo;',
  265. 'nextPageLabel' => '&rsaquo;',
  266. 'lastPageLabel' => '&raquo;',];
  267. $this->initColumns();
  268. }
  269. public function run()
  270. {
  271. $view = $this->getView();
  272. GridViewAsset::register($view);
  273. $this->registerGridJs();
  274. $this->registerIcheckJs();
  275. $this->registerConfirmJs();
  276. $this->registerExportJs();
  277. parent::run();
  278. }
  279. /**
  280. * 注册GridView Js
  281. */
  282. protected function registerGridJs()
  283. {
  284. $options = Json::htmlEncode(['filterUrl' => Url::to(Yii::$app->request->url),
  285. 'filterSelector' => $this->filterSelector]);
  286. $id = $this->options['id'];
  287. $this->getView()->registerJs("jQuery('#$id').yiiGridView($options);");
  288. }
  289. /**
  290. * 注册icheck Js
  291. */
  292. protected function registerIcheckJs()
  293. {
  294. $js = <<<SCRIPT
  295. $('.dataTable input[type="checkbox"]').iCheck({
  296. checkboxClass: 'icheckbox_flat-blue',
  297. radioClass: 'iradio_flat-blue'
  298. });
  299. $(".checkbox-toggle").click(function () {
  300. var clicks = $(this).data('clicks');
  301. if (clicks) {
  302. //Uncheck all checkboxes
  303. $(".dataTable input[type='checkbox']").iCheck("uncheck");
  304. $(".far", this).removeClass("fa-check-square").addClass('fa-square');
  305. } else {
  306. //Check all checkboxes
  307. $(".dataTable input[type='checkbox']").iCheck("check");
  308. $(".far", this).removeClass("fa-square").addClass('fa-check-square');
  309. }
  310. $(this).data("clicks", !clicks);
  311. });
  312. SCRIPT;
  313. $this->getView()->registerJs($js);
  314. }
  315. /**
  316. * 注册批量操作js
  317. */
  318. protected function registerBatchJs()
  319. {
  320. $js = <<<SCRIPT
  321. $("a.batch_item").click(function(){
  322. var url = $(this).data("url");
  323. var act = $(this).text();
  324. var selected = [];
  325. $(".checked input").each(function(){
  326. selected.push($(this).val());
  327. });
  328. if(selected.length > 0){
  329. alertify.confirm('系统提示', "确定执行批量 '"+act+"' 操作?", function(){
  330. $.ajax({
  331. type: "POST",
  332. url: url,
  333. traditional:true,
  334. data:{ 'ids[]':selected},
  335. dataType: "json",
  336. async:false
  337. });
  338. window.location.reload();
  339. },function(){
  340. });
  341. }
  342. return false;
  343. })
  344. SCRIPT;
  345. $this->getView()->registerJs($js);
  346. }
  347. protected function registerConfirmJs()
  348. {
  349. $js = <<<SCRIPT
  350. $("a[alertify-confirm]").click(function(){
  351. var message = $(this).attr('alertify-confirm');
  352. var url = $(this).attr('href');
  353. var id = $(this).data('id');
  354. alertify.confirm('系统提示', message,function(){
  355. $.ajax({
  356. type: "POST",
  357. url: url,
  358. traditional:true,
  359. data:{ id:id },
  360. dataType: "json",
  361. async:false
  362. });
  363. window.location.reload();
  364. },function(){
  365. });
  366. return false;
  367. });
  368. SCRIPT;
  369. $this->getView()->registerJs($js);
  370. }
  371. protected function registerExportJs()
  372. {
  373. $js = <<<SCRIPT
  374. $("a.export-all").click(function(url){
  375. var url = $(this).data("url");
  376. if(!location.search){
  377. window.location.replace(url+"?page-type=all");
  378. }else{
  379. window.location.replace(url+location.search+"&page-type=all");
  380. }
  381. });
  382. $("a.export-page").click(function(url){
  383. var url = $(this).data("url")+location.search;
  384. if(!location.search){
  385. window.location.replace(url+"?page-type=page");
  386. }else{
  387. window.location.replace(url+location.search+"&page-type=page");
  388. }
  389. });
  390. SCRIPT;
  391. $this->getView()->registerJs($js);
  392. }
  393. /**
  394. * 渲染局部
  395. * @return string|bool
  396. */
  397. public function renderSection($name)
  398. {
  399. switch ($name) {
  400. case '{summary}':
  401. return $this->renderSummary();
  402. case '{items}':
  403. return $this->renderItems();
  404. case '{pager}':
  405. return $this->renderPager();
  406. case '{sorter}':
  407. return $this->renderSorter();
  408. case '{filter}':
  409. return $this->renderFilter();
  410. case '{batch}':
  411. return $this->renderBatch();
  412. case '{url}':
  413. return Yii::$app->request->url;
  414. default:
  415. return false;
  416. }
  417. }
  418. /**
  419. * 渲染表格的html真实table
  420. * @return string
  421. */
  422. public function renderItems()
  423. {
  424. $tableHeader = $this->showHeader ? $this->renderTableHeader() : false;
  425. $tableBody = $this->renderTableBody();
  426. $content = array_filter([
  427. $tableHeader,
  428. $tableBody
  429. ]);
  430. return Html::tag('table', implode("\n", $content), $this->tableOptions);
  431. }
  432. /**
  433. * 初始化每列
  434. * @throws InvalidConfigException
  435. */
  436. protected function initColumns()
  437. {
  438. if (empty($this->columns)) {
  439. throw new InvalidConfigException('The "columns" property must be set.');
  440. }
  441. foreach ($this->columns as $i => $column) {
  442. if (is_string($column)) {
  443. $column = $this->createDataColumn($column);
  444. } else {
  445. $column = Yii::createObject(array_merge([
  446. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  447. 'grid' => $this,
  448. ], $column));
  449. }
  450. if (!$column->visible) {
  451. unset($this->columns[$i]);
  452. continue;
  453. }
  454. $this->columns[$i] = $column;
  455. }
  456. }
  457. /**
  458. * 渲染表头
  459. * @return string
  460. */
  461. public function renderTableHeader()
  462. {
  463. $cells = [];
  464. foreach ($this->columns as $column) {
  465. /* @var $column Column */
  466. $cells[] = $column->renderHeaderCell();
  467. }
  468. $content = Html::tag('tr', implode('', $cells), $this->headerRowOptions);
  469. return "<thead>\n" . $content . "\n</thead>";
  470. }
  471. /**
  472. * 渲染表格体
  473. * @return string
  474. */
  475. public function renderTableBody()
  476. {
  477. $models = $this->dataProvider->getModels();
  478. $keys = $this->dataProvider->getKeys();
  479. $rows = [];
  480. foreach ($models as $index => $model) {
  481. $key = $keys[$index];
  482. if ($this->beforeRow !== null) {
  483. $row = call_user_func($this->beforeRow, $model, $key, $index, $this);
  484. if (!empty($row)) {
  485. $rows[] = $row;
  486. }
  487. }
  488. $rows[] = $this->renderTableRow($model, $key, $index);
  489. if ($this->afterRow !== null) {
  490. $row = call_user_func($this->afterRow, $model, $key, $index, $this);
  491. if (!empty($row)) {
  492. $rows[] = $row;
  493. }
  494. }
  495. }
  496. if (empty($rows) && $this->emptyText !== false) {
  497. $colspan = count($this->columns);
  498. return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
  499. }
  500. return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
  501. }
  502. /**
  503. * 渲染表格的每行
  504. * @param Objetc $model
  505. * @param int $key
  506. * @param int $index
  507. * @return string
  508. */
  509. public function renderTableRow($model, $key, $index)
  510. {
  511. $cells = [];
  512. foreach ($this->columns as $column) {
  513. $cells[] = $column->renderDataCell($model, $key, $index);
  514. }
  515. if ($this->rowOptions instanceof Closure) {
  516. $options = call_user_func($this->rowOptions, $model, $key, $index, $this);
  517. } else {
  518. $options = $this->rowOptions;
  519. }
  520. $options['data-key'] = is_array($key) ? json_encode($key) : (string)$key;
  521. //TODO 各行变色放到这里不合理
  522. if ($index % 2 == 0) {
  523. $oddEven = 'odd';
  524. } else {
  525. $oddEven = 'even';
  526. }
  527. if (isset($options['class'])) {
  528. $options['class'] += " " . $oddEven;
  529. } else {
  530. $options['class'] = $oddEven;
  531. }
  532. return Html::tag('tr', implode('', $cells), $options);
  533. }
  534. /**
  535. * 渲染摘要显示
  536. * @return string
  537. */
  538. public function renderSummary()
  539. {
  540. $count = $this->dataProvider->getCount();
  541. if ($count <= 0) {
  542. return '';
  543. }
  544. $summaryOptions = $this->summaryOptions;
  545. $tag = ArrayHelper::remove($summaryOptions, 'tag', 'div');
  546. if (($pagination = $this->dataProvider->getPagination()) !== false) {
  547. $totalCount = $this->dataProvider->getTotalCount();
  548. $begin = $pagination->getPage() * $pagination->pageSize + 1;
  549. $end = $begin + $count - 1;
  550. if ($begin > $end) {
  551. $begin = $end;
  552. }
  553. $page = $pagination->getPage() + 1;
  554. $pageCount = $pagination->pageCount;
  555. }
  556. return Yii::$app->getI18n()->format($this->summary, [
  557. 'begin' => $begin,
  558. 'end' => $end,
  559. 'count' => $count,
  560. 'totalCount' => $totalCount,
  561. 'page' => $page,
  562. 'pageCount' => $pageCount,
  563. 'select' => $this->renderCountSelect()
  564. ], Yii::$app->language);
  565. }
  566. /**
  567. * 渲染批量操作
  568. */
  569. public function renderBatch()
  570. {
  571. if (empty($this->batch) && !is_array($this->batch)) {
  572. return "";
  573. }
  574. $this->registerBatchJs();
  575. $items = "";
  576. foreach ($this->batch as $item) {
  577. $items .= Html::tag('li', Html::a(Html::encode($item['label']), '#', ["data-url" => Html::encode($item['url']), "class" => "batch_item dropdown-item"]));
  578. }
  579. return strtr($this->batchTemplate, [
  580. "{items}" => $items
  581. ]);
  582. }
  583. /**
  584. * 渲染表格的页数select
  585. * @return string
  586. */
  587. protected function renderCountSelect()
  588. {
  589. $items = [
  590. "20" => 20,
  591. "50" => 50,
  592. "100" => 100
  593. ];
  594. $per = "条/页";
  595. $options = [];
  596. foreach ($items as $key => $val) {
  597. $options[$val] = "{$key}{$per}";
  598. }
  599. $perPage = !empty($_GET['per-page']) ? $_GET['per-page'] : 20;
  600. return Html::dropDownList('per-page', $perPage, $options, ["class" => "custom-select"]);
  601. }
  602. /**
  603. * 渲染表格的筛选部分
  604. * @return string
  605. */
  606. protected function renderFilter()
  607. {
  608. return $this->filter;
  609. }
  610. /**
  611. * 根据给定格式,创建一个 [[DataColumn]] 对象
  612. * @param string $text DataColumn 格式
  613. * @return DataColumn 实例
  614. * @throws InvalidConfigException
  615. */
  616. protected function createDataColumn($text)
  617. {
  618. if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
  619. throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  620. }
  621. return Yii::createObject([
  622. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  623. 'grid' => $this,
  624. 'attribute' => $matches[1],
  625. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  626. 'label' => isset($matches[5]) ? $matches[5] : null,
  627. ]);
  628. }
  629. }