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.

746 lines
22 KiB

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