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.

697 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="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="export">本页</a></li>
  204. <li> <a class="dropdown-item export-all" href="#" data-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. default:
  413. return false;
  414. }
  415. }
  416. /**
  417. * 渲染表格的html真实table
  418. * @return string
  419. */
  420. public function renderItems()
  421. {
  422. $tableHeader = $this->showHeader ? $this->renderTableHeader() : false;
  423. $tableBody = $this->renderTableBody();
  424. $content = array_filter([
  425. $tableHeader,
  426. $tableBody
  427. ]);
  428. return Html::tag('table', implode("\n", $content), $this->tableOptions);
  429. }
  430. /**
  431. * 初始化每列
  432. * @throws InvalidConfigException
  433. */
  434. protected function initColumns()
  435. {
  436. if (empty($this->columns)) {
  437. throw new InvalidConfigException('The "columns" property must be set.');
  438. }
  439. foreach ($this->columns as $i => $column) {
  440. if (is_string($column)) {
  441. $column = $this->createDataColumn($column);
  442. } else {
  443. $column = Yii::createObject(array_merge([
  444. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  445. 'grid' => $this,
  446. ], $column));
  447. }
  448. if (!$column->visible) {
  449. unset($this->columns[$i]);
  450. continue;
  451. }
  452. $this->columns[$i] = $column;
  453. }
  454. }
  455. /**
  456. * 渲染表头
  457. * @return string
  458. */
  459. public function renderTableHeader()
  460. {
  461. $cells = [];
  462. foreach ($this->columns as $column) {
  463. /* @var $column Column */
  464. $cells[] = $column->renderHeaderCell();
  465. }
  466. $content = Html::tag('tr', implode('', $cells), $this->headerRowOptions);
  467. return "<thead>\n" . $content . "\n</thead>";
  468. }
  469. /**
  470. * 渲染表格体
  471. * @return string
  472. */
  473. public function renderTableBody()
  474. {
  475. $models = $this->dataProvider->getModels();
  476. $keys = $this->dataProvider->getKeys();
  477. $rows = [];
  478. foreach ($models as $index => $model) {
  479. $key = $keys[$index];
  480. if ($this->beforeRow !== null) {
  481. $row = call_user_func($this->beforeRow, $model, $key, $index, $this);
  482. if (!empty($row)) {
  483. $rows[] = $row;
  484. }
  485. }
  486. $rows[] = $this->renderTableRow($model, $key, $index);
  487. if ($this->afterRow !== null) {
  488. $row = call_user_func($this->afterRow, $model, $key, $index, $this);
  489. if (!empty($row)) {
  490. $rows[] = $row;
  491. }
  492. }
  493. }
  494. if (empty($rows) && $this->emptyText !== false) {
  495. $colspan = count($this->columns);
  496. return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
  497. }
  498. return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
  499. }
  500. /**
  501. * 渲染表格的每行
  502. * @param Objetc $model
  503. * @param int $key
  504. * @param int $index
  505. * @return string
  506. */
  507. public function renderTableRow($model, $key, $index)
  508. {
  509. $cells = [];
  510. foreach ($this->columns as $column) {
  511. $cells[] = $column->renderDataCell($model, $key, $index);
  512. }
  513. if ($this->rowOptions instanceof Closure) {
  514. $options = call_user_func($this->rowOptions, $model, $key, $index, $this);
  515. } else {
  516. $options = $this->rowOptions;
  517. }
  518. $options['data-key'] = is_array($key) ? json_encode($key) : (string)$key;
  519. //TODO 各行变色放到这里不合理
  520. if ($index % 2 == 0) {
  521. $oddEven = 'odd';
  522. } else {
  523. $oddEven = 'even';
  524. }
  525. if (isset($options['class'])) {
  526. $options['class'] += " " . $oddEven;
  527. } else {
  528. $options['class'] = $oddEven;
  529. }
  530. return Html::tag('tr', implode('', $cells), $options);
  531. }
  532. /**
  533. * 渲染摘要显示
  534. * @return string
  535. */
  536. public function renderSummary()
  537. {
  538. $count = $this->dataProvider->getCount();
  539. if ($count <= 0) {
  540. return '';
  541. }
  542. $summaryOptions = $this->summaryOptions;
  543. $tag = ArrayHelper::remove($summaryOptions, 'tag', 'div');
  544. if (($pagination = $this->dataProvider->getPagination()) !== false) {
  545. $totalCount = $this->dataProvider->getTotalCount();
  546. $begin = $pagination->getPage() * $pagination->pageSize + 1;
  547. $end = $begin + $count - 1;
  548. if ($begin > $end) {
  549. $begin = $end;
  550. }
  551. $page = $pagination->getPage() + 1;
  552. $pageCount = $pagination->pageCount;
  553. }
  554. return Yii::$app->getI18n()->format($this->summary, [
  555. 'begin' => $begin,
  556. 'end' => $end,
  557. 'count' => $count,
  558. 'totalCount' => $totalCount,
  559. 'page' => $page,
  560. 'pageCount' => $pageCount,
  561. 'select' => $this->renderCountSelect()
  562. ], Yii::$app->language);
  563. }
  564. /**
  565. * 渲染批量操作
  566. */
  567. public function renderBatch()
  568. {
  569. if (empty($this->batch) && !is_array($this->batch)) {
  570. return "";
  571. }
  572. $this->registerBatchJs();
  573. $items = "";
  574. foreach ($this->batch as $item) {
  575. $items .= Html::tag('li', Html::a(Html::encode($item['label']), '#', ["data-url" => Html::encode($item['url']), "class" => "batch_item dropdown-item"]));
  576. }
  577. return strtr($this->batchTemplate, [
  578. "{items}" => $items
  579. ]);
  580. }
  581. /**
  582. * 渲染表格的页数select
  583. * @return string
  584. */
  585. protected function renderCountSelect()
  586. {
  587. $items = [
  588. "20" => 20,
  589. "50" => 50,
  590. "100" => 100
  591. ];
  592. $per = "条/页";
  593. $options = [];
  594. foreach ($items as $key => $val) {
  595. $options[$val] = "{$key}{$per}";
  596. }
  597. $perPage = !empty($_GET['per-page']) ? $_GET['per-page'] : 20;
  598. return Html::dropDownList('per-page', $perPage, $options, ["class" => "custom-select"]);
  599. }
  600. /**
  601. * 渲染表格的筛选部分
  602. * @return string
  603. */
  604. protected function renderFilter()
  605. {
  606. return $this->filter;
  607. }
  608. /**
  609. * 根据给定格式,创建一个 [[DataColumn]] 对象
  610. * @param string $text DataColumn 格式
  611. * @return DataColumn 实例
  612. * @throws InvalidConfigException
  613. */
  614. protected function createDataColumn($text)
  615. {
  616. if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
  617. throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  618. }
  619. return Yii::createObject([
  620. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  621. 'grid' => $this,
  622. 'attribute' => $matches[1],
  623. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  624. 'label' => isset($matches[5]) ? $matches[5] : null,
  625. ]);
  626. }
  627. }