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.

748 lines
22 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  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. {create}
  199. <!-- <a href="#" data-url='export' class="export btn btn-default"><i class="fa fa-file-excel-o"></i>导出</a>-->
  200. {export}
  201. <!-- <button type="button" id="export" class="btn btn-default"><i class="fa fa-file-excel-o"></i>导出</button>-->
  202. {content}
  203. </div>
  204. <div class="col-sm-12 col-md-6">
  205. {filter}
  206. </div>
  207. </div>
  208. <div class="row">
  209. <div class="col-sm-12">
  210. {items}
  211. </div>
  212. </div>
  213. <div class="row">
  214. <div class="col-sm-12 col-md-5">
  215. <div class="dataTables_length" id="example2_info" role="status" aria-live="polite">
  216. {summary}
  217. </div>
  218. </div>
  219. <div class="col-sm-12 col-md-7">
  220. <div class="dataTables_paginate paging_simple_numbers">
  221. {pager}
  222. </div>
  223. </div>
  224. </div>
  225. </div>
  226. </div>
  227. HTML;
  228. public $batchTemplate = <<< HTML
  229. <div class="btn-group">
  230. <button type="button" class="btn btn-default btn checkbox-toggle"><i class="far fa-square"></i></button>
  231. <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">批量操作</button>
  232. <ul class="dropdown-menu" role="menu">
  233. {items}
  234. </ul>
  235. </div>
  236. HTML;
  237. public $export =<<<HTML
  238. <div class="btn-group">
  239. <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>
  240. <ul class="dropdown-menu" role="menu">
  241. <li> <a class="dropdown-item export-page" href="#" data-url="{url}/export">本页</a></li>
  242. <li> <a class="dropdown-item export-all" href="#" data-url="{url}/export">全部</a></li>
  243. </ul>
  244. </div>
  245. HTML;
  246. public $create =<<<HTML
  247. <a href="create" class="btn btn-default"><i class="fas fa-plus-square mr-2"></i>添加</a>
  248. HTML;
  249. /**
  250. * @var
  251. * 表单头部内容
  252. */
  253. public $content;
  254. /**
  255. * 初始化 grid view.
  256. * 初始化必须的属性和每个列对象
  257. * @return
  258. */
  259. public function init()
  260. {
  261. parent::init();
  262. if ($this->formatter === null) {
  263. $this->formatter = Yii::$app->getFormatter();
  264. } elseif (is_array($this->formatter)) {
  265. $this->formatter = Yii::createObject($this->formatter);
  266. }
  267. if (!$this->formatter instanceof Formatter) {
  268. throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
  269. }
  270. $this->pager = [
  271. 'options' => ['class' => ['justify-content-end', 'pagination']],
  272. 'linkOptions' => ['class' => 'page-link'],
  273. 'pageCssClass' => 'paginate_button page-item',
  274. 'disabledPageCssClass' => 'page-link disabled',
  275. 'firstPageLabel' => '&laquo;',
  276. 'prevPageLabel' => '&lsaquo;',
  277. 'nextPageLabel' => '&rsaquo;',
  278. 'lastPageLabel' => '&raquo;',];
  279. $this->initColumns();
  280. }
  281. public function run()
  282. {
  283. $view = $this->getView();
  284. GridViewAsset::register($view);
  285. $this->registerGridJs();
  286. $this->registerIcheckJs();
  287. $this->registerConfirmJs();
  288. $this->registerExportJs();
  289. parent::run();
  290. }
  291. /**
  292. * 注册GridView Js
  293. */
  294. protected function registerGridJs()
  295. {
  296. $options = Json::htmlEncode(['filterUrl' => Url::to(Yii::$app->request->url),
  297. 'filterSelector' => $this->filterSelector]);
  298. $id = $this->options['id'];
  299. $this->getView()->registerJs("jQuery('#$id').yiiGridView($options);");
  300. }
  301. /**
  302. * 注册icheck Js
  303. */
  304. protected function registerIcheckJs()
  305. {
  306. $js = <<<SCRIPT
  307. $('.dataTable input[type="checkbox"]').iCheck({
  308. checkboxClass: 'icheckbox_flat-blue',
  309. radioClass: 'iradio_flat-blue'
  310. });
  311. $(".checkbox-toggle").click(function () {
  312. var clicks = $(this).data('clicks');
  313. if (clicks) {
  314. //Uncheck all checkboxes
  315. $(".dataTable input[type='checkbox']").iCheck("uncheck");
  316. $(".far", this).removeClass("fa-check-square").addClass('fa-square');
  317. } else {
  318. //Check all checkboxes
  319. $(".dataTable input[type='checkbox']").iCheck("check");
  320. $(".far", this).removeClass("fa-square").addClass('fa-check-square');
  321. }
  322. $(this).data("clicks", !clicks);
  323. });
  324. SCRIPT;
  325. $this->getView()->registerJs($js);
  326. }
  327. /**
  328. * 注册批量操作js
  329. */
  330. protected function registerBatchJs()
  331. {
  332. $js = <<<SCRIPT
  333. $("a.batch_item").click(function(){
  334. var url = $(this).data("url");
  335. var act = $(this).text();
  336. var selected = [];
  337. $(".checked input").each(function(){
  338. selected.push($(this).val());
  339. });
  340. if(selected.length > 0){
  341. alertify.confirm('系统提示', "确定执行批量 '"+act+"' 操作?", function(){
  342. $.ajax({
  343. type: "POST",
  344. url: url,
  345. traditional:true,
  346. data:{ 'ids[]':selected},
  347. dataType: "json",
  348. async:false
  349. });
  350. window.location.reload();
  351. },function(){
  352. });
  353. }
  354. return false;
  355. })
  356. SCRIPT;
  357. $this->getView()->registerJs($js);
  358. }
  359. protected function registerConfirmJs()
  360. {
  361. $js = <<<SCRIPT
  362. $("a[alertify-confirm]").click(function(){
  363. var message = $(this).attr('alertify-confirm');
  364. var url = $(this).attr('href');
  365. var id = $(this).data('id');
  366. alertify.confirm('系统提示', message,function(){
  367. $.ajax({
  368. type: "POST",
  369. url: url,
  370. traditional:true,
  371. data:{ id:id },
  372. dataType: "json",
  373. async:false
  374. });
  375. window.location.reload();
  376. },function(){
  377. });
  378. return false;
  379. });
  380. SCRIPT;
  381. $this->getView()->registerJs($js);
  382. }
  383. protected function registerExportJs()
  384. {
  385. $js = <<<SCRIPT
  386. $("a.export-all").click(function(url){
  387. var url = $(this).data("url");
  388. if(!location.search){
  389. window.location.replace(url+"?page-type=all");
  390. }else{
  391. window.location.replace(url+location.search+"&page-type=all");
  392. }
  393. });
  394. $("a.export-page").click(function(url){
  395. var url = $(this).data("url")+location.search;
  396. if(!location.search){
  397. window.location.replace(url+"?page-type=page");
  398. }else{
  399. window.location.replace(url+location.search+"&page-type=page");
  400. }
  401. });
  402. SCRIPT;
  403. $this->getView()->registerJs($js);
  404. }
  405. /**
  406. * 渲染局部
  407. * @return string|bool
  408. */
  409. public function renderSection($name)
  410. {
  411. switch ($name) {
  412. case '{summary}':
  413. return $this->renderSummary();
  414. case '{items}':
  415. return $this->renderItems();
  416. case '{pager}':
  417. return $this->renderPager();
  418. case '{sorter}':
  419. return $this->renderSorter();
  420. case '{filter}':
  421. return $this->renderFilter();
  422. case '{batch}':
  423. return $this->renderBatch();
  424. case '{url}':
  425. return Yii::$app->request->url;
  426. case '{export}':
  427. return $this->renderExport();
  428. case '{create}':
  429. return $this->renderCreate();
  430. case '{content}':
  431. return $this->renderContent();
  432. default:
  433. return false;
  434. }
  435. }
  436. /**
  437. * 渲染表格的html真实table
  438. * @return string
  439. */
  440. public function renderItems()
  441. {
  442. $tableHeader = $this->showHeader ? $this->renderTableHeader() : false;
  443. $tableBody = $this->renderTableBody();
  444. $content = array_filter([
  445. $tableHeader,
  446. $tableBody
  447. ]);
  448. return Html::tag('table', implode("\n", $content), $this->tableOptions);
  449. }
  450. /**
  451. * 初始化每列
  452. * @throws InvalidConfigException
  453. */
  454. protected function initColumns()
  455. {
  456. if (empty($this->columns)) {
  457. throw new InvalidConfigException('The "columns" property must be set.');
  458. }
  459. foreach ($this->columns as $i => $column) {
  460. if (is_string($column)) {
  461. $column = $this->createDataColumn($column);
  462. } else {
  463. $column = Yii::createObject(array_merge([
  464. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  465. 'grid' => $this,
  466. ], $column));
  467. }
  468. if (!$column->visible) {
  469. unset($this->columns[$i]);
  470. continue;
  471. }
  472. $this->columns[$i] = $column;
  473. }
  474. }
  475. /**
  476. * 渲染表头
  477. * @return string
  478. */
  479. public function renderTableHeader()
  480. {
  481. $cells = [];
  482. foreach ($this->columns as $column) {
  483. /* @var $column Column */
  484. $cells[] = $column->renderHeaderCell();
  485. }
  486. $content = Html::tag('tr', implode('', $cells), $this->headerRowOptions);
  487. return "<thead>\n" . $content . "\n</thead>";
  488. }
  489. /**
  490. * 渲染表格体
  491. * @return string
  492. */
  493. public function renderTableBody()
  494. {
  495. $models = $this->dataProvider->getModels();
  496. $keys = $this->dataProvider->getKeys();
  497. $rows = [];
  498. foreach ($models as $index => $model) {
  499. $key = $keys[$index];
  500. if ($this->beforeRow !== null) {
  501. $row = call_user_func($this->beforeRow, $model, $key, $index, $this);
  502. if (!empty($row)) {
  503. $rows[] = $row;
  504. }
  505. }
  506. $rows[] = $this->renderTableRow($model, $key, $index);
  507. if ($this->afterRow !== null) {
  508. $row = call_user_func($this->afterRow, $model, $key, $index, $this);
  509. if (!empty($row)) {
  510. $rows[] = $row;
  511. }
  512. }
  513. }
  514. if (empty($rows) && $this->emptyText !== false) {
  515. $colspan = count($this->columns);
  516. return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
  517. }
  518. return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
  519. }
  520. /**
  521. * 渲染表格的每行
  522. * @param Objetc $model
  523. * @param int $key
  524. * @param int $index
  525. * @return string
  526. */
  527. public function renderTableRow($model, $key, $index)
  528. {
  529. $cells = [];
  530. foreach ($this->columns as $column) {
  531. $cells[] = $column->renderDataCell($model, $key, $index);
  532. }
  533. if ($this->rowOptions instanceof Closure) {
  534. $options = call_user_func($this->rowOptions, $model, $key, $index, $this);
  535. } else {
  536. $options = $this->rowOptions;
  537. }
  538. $options['data-key'] = is_array($key) ? json_encode($key) : (string)$key;
  539. //TODO 各行变色放到这里不合理
  540. if ($index % 2 == 0) {
  541. $oddEven = 'odd';
  542. } else {
  543. $oddEven = 'even';
  544. }
  545. if (isset($options['class'])) {
  546. $options['class'] += " " . $oddEven;
  547. } else {
  548. $options['class'] = $oddEven;
  549. }
  550. return Html::tag('tr', implode('', $cells), $options);
  551. }
  552. /**
  553. * 渲染摘要显示
  554. * @return string
  555. */
  556. public function renderSummary()
  557. {
  558. $count = $this->dataProvider->getCount();
  559. if ($count <= 0) {
  560. return '';
  561. }
  562. $summaryOptions = $this->summaryOptions;
  563. $tag = ArrayHelper::remove($summaryOptions, 'tag', 'div');
  564. if (($pagination = $this->dataProvider->getPagination()) !== false) {
  565. $totalCount = $this->dataProvider->getTotalCount();
  566. $begin = $pagination->getPage() * $pagination->pageSize + 1;
  567. $end = $begin + $count - 1;
  568. if ($begin > $end) {
  569. $begin = $end;
  570. }
  571. $page = $pagination->getPage() + 1;
  572. $pageCount = $pagination->pageCount;
  573. }
  574. return Yii::$app->getI18n()->format($this->summary, [
  575. 'begin' => $begin,
  576. 'end' => $end,
  577. 'count' => $count,
  578. 'totalCount' => $totalCount,
  579. 'page' => $page,
  580. 'pageCount' => $pageCount,
  581. 'select' => $this->renderCountSelect()
  582. ], Yii::$app->language);
  583. }
  584. /**
  585. * 渲染批量操作
  586. */
  587. public function renderBatch()
  588. {
  589. if (empty($this->batch) && !is_array($this->batch)) {
  590. return "";
  591. }
  592. $this->registerBatchJs();
  593. $items = "";
  594. foreach ($this->batch as $item) {
  595. $items .= Html::tag('li', Html::a(Html::encode($item['label']), '#', ["data-url" => Html::encode($item['url']), "class" => "batch_item dropdown-item"]));
  596. }
  597. return strtr($this->batchTemplate, [
  598. "{items}" => $items
  599. ]);
  600. }
  601. /**
  602. * 渲染表格的页数select
  603. * @return string
  604. */
  605. protected function renderCountSelect()
  606. {
  607. $items = [
  608. "20" => 20,
  609. "50" => 50,
  610. "100" => 100
  611. ];
  612. $per = "条/页";
  613. $options = [];
  614. foreach ($items as $key => $val) {
  615. $options[$val] = "{$key}{$per}";
  616. }
  617. $perPage = !empty($_GET['per-page']) ? $_GET['per-page'] : 20;
  618. return Html::dropDownList('per-page', $perPage, $options, ["class" => "custom-select"]);
  619. }
  620. /**
  621. * 渲染表格的筛选部分
  622. * @return string
  623. */
  624. protected function renderFilter()
  625. {
  626. return $this->filter;
  627. }
  628. /**
  629. * 根据给定格式,创建一个 [[DataColumn]] 对象
  630. * @param string $text DataColumn 格式
  631. * @return DataColumn 实例
  632. * @throws InvalidConfigException
  633. */
  634. protected function createDataColumn($text)
  635. {
  636. if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
  637. throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  638. }
  639. return Yii::createObject([
  640. 'class' => $this->dataColumnClass ?: DataColumn::className(),
  641. 'grid' => $this,
  642. 'attribute' => $matches[1],
  643. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  644. 'label' => isset($matches[5]) ? $matches[5] : null,
  645. ]);
  646. }
  647. /**
  648. * 渲染导出部分
  649. * @return string
  650. */
  651. protected function renderExport()
  652. {
  653. return $this->export;
  654. }
  655. /**
  656. * 渲染创建部分
  657. * @return string
  658. */
  659. protected function renderCreate()
  660. {
  661. return $this->create;
  662. }
  663. /**
  664. * 渲染表单头部内容
  665. * @return string
  666. */
  667. protected function renderContent()
  668. {
  669. return Html::tag('div', $this->content, ['class' => 'btn-group']);
  670. }
  671. }