Grid.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Contracts\Repository;
  5. use Dcat\Admin\Grid\Column;
  6. use Dcat\Admin\Grid\Concerns;
  7. use Dcat\Admin\Grid\Model;
  8. use Dcat\Admin\Grid\Responsive;
  9. use Dcat\Admin\Grid\Row;
  10. use Dcat\Admin\Grid\Tools;
  11. use Dcat\Admin\Support\Helper;
  12. use Dcat\Admin\Traits\HasBuilderEvents;
  13. use Illuminate\Contracts\Support\Renderable;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Support\Collection;
  16. use Illuminate\Support\Str;
  17. use Illuminate\Support\Traits\Macroable;
  18. class Grid
  19. {
  20. use HasBuilderEvents,
  21. Concerns\HasNames,
  22. Concerns\HasFilter,
  23. Concerns\HasTools,
  24. Concerns\HasActions,
  25. Concerns\HasPaginator,
  26. Concerns\HasExporter,
  27. Concerns\HasComplexHeaders,
  28. Concerns\HasSelector,
  29. Concerns\HasQuickCreate,
  30. Concerns\HasQuickSearch,
  31. Macroable {
  32. __call as macroCall;
  33. }
  34. const CREATE_MODE_DEFAULT = 'default';
  35. const CREATE_MODE_DIALOG = 'dialog';
  36. /**
  37. * The grid data model instance.
  38. *
  39. * @var \Dcat\Admin\Grid\Model
  40. */
  41. protected $model;
  42. /**
  43. * Collection of all grid columns.
  44. *
  45. * @var \Illuminate\Support\Collection
  46. */
  47. protected $columns;
  48. /**
  49. * Collection of all data rows.
  50. *
  51. * @var \Illuminate\Support\Collection
  52. */
  53. protected $rows;
  54. /**
  55. * Rows callable fucntion.
  56. *
  57. * @var \Closure[]
  58. */
  59. protected $rowsCallback = [];
  60. /**
  61. * All column names of the grid.
  62. *
  63. * @var array
  64. */
  65. protected $columnNames = [];
  66. /**
  67. * Grid builder.
  68. *
  69. * @var \Closure
  70. */
  71. protected $builder;
  72. /**
  73. * Mark if the grid is built.
  74. *
  75. * @var bool
  76. */
  77. protected $built = false;
  78. /**
  79. * All variables in grid view.
  80. *
  81. * @var array
  82. */
  83. protected $variables = [];
  84. /**
  85. * Resource path of the grid.
  86. *
  87. * @var
  88. */
  89. protected $resourcePath;
  90. /**
  91. * Default primary key name.
  92. *
  93. * @var string
  94. */
  95. protected $keyName = 'id';
  96. /**
  97. * View for grid to render.
  98. *
  99. * @var string
  100. */
  101. protected $view = 'admin::grid.table2';
  102. /**
  103. * @var Closure
  104. */
  105. protected $header;
  106. /**
  107. * @var Closure
  108. */
  109. protected $footer;
  110. /**
  111. * @var Closure
  112. */
  113. protected $wrapper;
  114. /**
  115. * @var Responsive
  116. */
  117. protected $responsive;
  118. /**
  119. * @var bool
  120. */
  121. protected $addNumberColumn = false;
  122. /**
  123. * @var string
  124. */
  125. protected $tableId = 'grid-table';
  126. /**
  127. * @var Grid\Tools\RowSelector
  128. */
  129. protected $rowSelector;
  130. /**
  131. * Options for grid.
  132. *
  133. * @var array
  134. */
  135. protected $options = [
  136. 'show_pagination' => true,
  137. 'show_filter' => true,
  138. 'show_actions' => true,
  139. 'show_quick_edit_button' => false,
  140. 'show_edit_button' => true,
  141. 'show_view_button' => true,
  142. 'show_delete_button' => true,
  143. 'show_row_selector' => true,
  144. 'show_create_button' => true,
  145. 'show_bordered' => false,
  146. 'show_toolbar' => true,
  147. 'create_mode' => self::CREATE_MODE_DEFAULT,
  148. 'dialog_form_area' => ['700px', '670px'],
  149. 'table_header_style' => 'table-header-gray',
  150. ];
  151. /**
  152. * Create a new grid instance.
  153. *
  154. * Grid constructor.
  155. *
  156. * @param Repository|\Illuminate\Database\Eloquent\Model|Builder|null $repository
  157. * @param null|\Closure $builder
  158. */
  159. public function __construct($repository = null, ?\Closure $builder = null)
  160. {
  161. $this->model = new Model(request(), $repository);
  162. $this->columns = new Collection();
  163. $this->rows = new Collection();
  164. $this->builder = $builder;
  165. if ($repository = $this->model->repository()) {
  166. $this->setKeyName($repository->getKeyName());
  167. }
  168. $this->model->setGrid($this);
  169. $this->setupTools();
  170. $this->setupFilter();
  171. $this->callResolving();
  172. }
  173. /**
  174. * Get table ID.
  175. *
  176. * @return string
  177. */
  178. public function getTableId()
  179. {
  180. return $this->tableId;
  181. }
  182. /**
  183. * Set primary key name.
  184. *
  185. * @param string $name
  186. *
  187. * @return $this
  188. */
  189. public function setKeyName(string $name)
  190. {
  191. $this->keyName = $name;
  192. return $this;
  193. }
  194. /**
  195. * Get or set primary key name.
  196. *
  197. * @return string|void
  198. */
  199. public function getKeyName()
  200. {
  201. return $this->keyName ?: 'id';
  202. }
  203. /**
  204. * Add column to Grid.
  205. *
  206. * @param string $name
  207. * @param string $label
  208. *
  209. * @return Column
  210. */
  211. public function column($name, $label = '')
  212. {
  213. if (strpos($name, '.') !== false) {
  214. [$relationName, $relationColumn] = explode('.', $name);
  215. $label = empty($label) ? admin_trans_field($relationColumn) : $label;
  216. $name = Str::snake($relationName).'.'.$relationColumn;
  217. }
  218. $column = $this->addColumn($name, $label);
  219. return $column;
  220. }
  221. /**
  222. * Add number column.
  223. *
  224. * @param null|string $label
  225. *
  226. * @return Column
  227. */
  228. public function number(?string $label = null)
  229. {
  230. return $this->addColumn('#', $label ?: '#')->bold();
  231. }
  232. /**
  233. * Batch add column to grid.
  234. *
  235. * @example
  236. * 1.$grid->columns(['name' => 'Name', 'email' => 'Email' ...]);
  237. * 2.$grid->columns('name', 'email' ...)
  238. *
  239. * @param array $columns
  240. *
  241. * @return Collection|void
  242. */
  243. public function columns($columns = null)
  244. {
  245. if ($columns === null) {
  246. return $this->columns;
  247. }
  248. if (func_num_args() == 1 && is_array($columns)) {
  249. foreach ($columns as $column => $label) {
  250. $this->column($column, $label);
  251. }
  252. return;
  253. }
  254. foreach (func_get_args() as $column) {
  255. $this->column($column);
  256. }
  257. }
  258. /**
  259. * Add column to grid.
  260. *
  261. * @param string $field
  262. * @param string $label
  263. *
  264. * @return Column
  265. */
  266. protected function addColumn($field = '', $label = '')
  267. {
  268. $column = $this->newColumn($field, $label);
  269. $this->columns->put($field, $column);
  270. return $column;
  271. }
  272. /**
  273. * @param string $field
  274. * @param string $label
  275. *
  276. * @return Column
  277. */
  278. public function newColumn($field = '', $label = '')
  279. {
  280. $column = new Column($field, $label);
  281. $column->setGrid($this);
  282. return $column;
  283. }
  284. /**
  285. * Get Grid model.
  286. *
  287. * @return Model
  288. */
  289. public function model()
  290. {
  291. return $this->model;
  292. }
  293. /**
  294. * @return array
  295. */
  296. public function getColumnNames()
  297. {
  298. return $this->columnNames;
  299. }
  300. /**
  301. * Apply column filter to grid query.
  302. */
  303. protected function applyColumnFilter()
  304. {
  305. $this->columns->each->bindFilterQuery($this->model());
  306. }
  307. /**
  308. * Build the grid.
  309. *
  310. * @return void
  311. */
  312. public function build()
  313. {
  314. if ($this->built) {
  315. return;
  316. }
  317. $collection = $this->processFilter(false);
  318. $data = $collection->toArray();
  319. $this->prependRowSelectorColumn();
  320. $this->appendActionsColumn();
  321. Column::setOriginalGridModels($collection);
  322. $this->columns->map(function (Column $column) use (&$data) {
  323. $column->fill($data);
  324. $this->columnNames[] = $column->getName();
  325. });
  326. $this->buildRows($data);
  327. if ($data && $this->responsive) {
  328. $this->responsive->build();
  329. }
  330. $this->sortHeaders();
  331. }
  332. /**
  333. * @return void
  334. */
  335. protected function callBuilder()
  336. {
  337. if ($this->builder && ! $this->built) {
  338. call_user_func($this->builder, $this);
  339. }
  340. $this->built = true;
  341. }
  342. /**
  343. * Build the grid rows.
  344. *
  345. * @param array $data
  346. *
  347. * @return void
  348. */
  349. protected function buildRows(array $data)
  350. {
  351. $this->rows = collect($data)->map(function ($model) {
  352. return new Row($this, $model);
  353. });
  354. if ($this->rowsCallback) {
  355. foreach ($this->rowsCallback as $value) {
  356. $value($this->rows);
  357. }
  358. }
  359. }
  360. /**
  361. * Set grid row callback function.
  362. *
  363. * @param Closure $callable
  364. *
  365. * @return Collection|void
  366. */
  367. public function rows(Closure $callable = null)
  368. {
  369. if (is_null($callable)) {
  370. return $this->rows;
  371. }
  372. $this->rowsCallback[] = $callable;
  373. }
  374. /**
  375. * Get create url.
  376. *
  377. * @return string
  378. */
  379. public function getCreateUrl()
  380. {
  381. $queryString = '';
  382. if ($constraints = $this->model()->getConstraints()) {
  383. $queryString = http_build_query($constraints);
  384. }
  385. return sprintf(
  386. '%s/create%s',
  387. $this->resource(),
  388. $queryString ? ('?'.$queryString) : ''
  389. );
  390. }
  391. /**
  392. * @param \Closure $closure
  393. *
  394. * @return Grid\Tools\RowSelector
  395. */
  396. public function rowSelector()
  397. {
  398. return $this->rowSelector ?: ($this->rowSelector = new Grid\Tools\RowSelector($this));
  399. }
  400. /**
  401. * Prepend checkbox column for grid.
  402. *
  403. * @return void
  404. */
  405. protected function prependRowSelectorColumn()
  406. {
  407. if (! $this->options['show_row_selector']) {
  408. return;
  409. }
  410. $rowSelector = $this->rowSelector();
  411. $keyName = $this->getKeyName();
  412. $column = $this->newColumn(
  413. Grid\Column::SELECT_COLUMN_NAME,
  414. $rowSelector->renderHeader()
  415. );
  416. $column->setGrid($this);
  417. $column->display(function () use ($rowSelector, $keyName) {
  418. return $rowSelector->renderColumn($this, $this->{$keyName});
  419. });
  420. $this->columns->prepend($column, Grid\Column::SELECT_COLUMN_NAME);
  421. }
  422. /**
  423. * @param string $width
  424. * @param string $height
  425. *
  426. * @return $this
  427. */
  428. public function setDialogFormDimensions(string $width, string $height)
  429. {
  430. $this->options['dialog_form_area'] = [$width, $height];
  431. return $this;
  432. }
  433. /**
  434. * Render create button for grid.
  435. *
  436. * @return string
  437. */
  438. public function renderCreateButton()
  439. {
  440. if (! $this->options['show_create_button']) {
  441. return '';
  442. }
  443. return (new Tools\CreateButton($this))->render();
  444. }
  445. /**
  446. * @return $this
  447. */
  448. public function withBorder()
  449. {
  450. $this->options['show_bordered'] = true;
  451. return $this;
  452. }
  453. /**
  454. * Set grid header.
  455. *
  456. * @param Closure|string|Renderable $content
  457. *
  458. * @return $this|Closure
  459. */
  460. public function header($content = null)
  461. {
  462. if (! $content) {
  463. return $this->header;
  464. }
  465. $this->header = $content;
  466. return $this;
  467. }
  468. /**
  469. * Render grid header.
  470. *
  471. * @return string
  472. */
  473. public function renderHeader()
  474. {
  475. if (! $this->header) {
  476. return '';
  477. }
  478. $content = Helper::render($this->header, [$this->processFilter(false)]);
  479. if (empty($content)) {
  480. return '';
  481. }
  482. return <<<HTML
  483. <div class="box-header clearfix" style="border-top:1px solid #ebeff2">{$content}</div>
  484. HTML;
  485. }
  486. /**
  487. * Set grid footer.
  488. *
  489. * @param Closure|string|Renderable $content
  490. *
  491. * @return $this|Closure
  492. */
  493. public function footer($content = null)
  494. {
  495. if (! $content) {
  496. return $this->footer;
  497. }
  498. $this->footer = $content;
  499. return $this;
  500. }
  501. /**
  502. * Render grid footer.
  503. *
  504. * @return string
  505. */
  506. public function renderFooter()
  507. {
  508. if (! $this->footer) {
  509. return '';
  510. }
  511. $content = Helper::render($this->footer, [$this->processFilter(false)]);
  512. if (empty($content)) {
  513. return '';
  514. }
  515. return <<<HTML
  516. <div class="box-footer clearfix">{$content}</div>
  517. HTML;
  518. }
  519. /**
  520. * Get or set option for grid.
  521. *
  522. * @param string $key
  523. * @param mixed $value
  524. *
  525. * @return $this|mixed
  526. */
  527. public function option($key, $value = null)
  528. {
  529. if (is_null($value)) {
  530. return $this->options[$key];
  531. }
  532. $this->options[$key] = $value;
  533. return $this;
  534. }
  535. /**
  536. * Disable row selector.
  537. *
  538. * @return $this
  539. */
  540. public function disableRowSelector(bool $disable = true)
  541. {
  542. $this->tools->disableBatchActions($disable);
  543. return $this->option('show_row_selector', ! $disable);
  544. }
  545. /**
  546. * Show row selector.
  547. *
  548. * @return $this
  549. */
  550. public function showRowSelector(bool $val = true)
  551. {
  552. return $this->disableRowSelector(! $val);
  553. }
  554. /**
  555. * Remove create button on grid.
  556. *
  557. * @return $this
  558. */
  559. public function disableCreateButton(bool $disable = true)
  560. {
  561. return $this->option('show_create_button', ! $disable);
  562. }
  563. /**
  564. * Show create button.
  565. *
  566. * @return $this
  567. */
  568. public function showCreateButton(bool $val = true)
  569. {
  570. return $this->disableCreateButton(! $val);
  571. }
  572. /**
  573. * If allow creation.
  574. *
  575. * @return bool
  576. */
  577. public function allowCreateButton()
  578. {
  579. return $this->options['show_create_button'];
  580. }
  581. /**
  582. * @param string $mode
  583. *
  584. * @return $this
  585. */
  586. public function createMode(string $mode)
  587. {
  588. return $this->option('create_mode', $mode);
  589. }
  590. /**
  591. * @return $this
  592. */
  593. public function enableDialogCreate()
  594. {
  595. return $this->createMode(self::CREATE_MODE_DIALOG);
  596. }
  597. /**
  598. * Get or set resource path.
  599. *
  600. * @param string $path
  601. *
  602. * @return $this|string
  603. */
  604. public function resource(string $path = null)
  605. {
  606. if ($path === null) {
  607. return $this->resourcePath ?: (
  608. $this->resourcePath = url(app('request')->getPathInfo())
  609. );
  610. }
  611. if (! empty($path)) {
  612. $this->resourcePath = admin_url($path);
  613. }
  614. return $this;
  615. }
  616. /**
  617. * Create a grid instance.
  618. *
  619. * @param mixed ...$params
  620. *
  621. * @return $this
  622. */
  623. public static function make(...$params)
  624. {
  625. return new static(...$params);
  626. }
  627. /**
  628. * Enable responsive tables.
  629. *
  630. * @see https://github.com/nadangergeo/RWD-Table-Patterns
  631. *
  632. * @return Responsive
  633. */
  634. public function responsive()
  635. {
  636. if (! $this->responsive) {
  637. $this->responsive = new Responsive($this);
  638. }
  639. return $this->responsive;
  640. }
  641. /**
  642. * @return bool
  643. */
  644. public function allowResponsive()
  645. {
  646. return $this->responsive ? true : false;
  647. }
  648. /**
  649. * @param Closure $closure
  650. *
  651. * @return $this;
  652. */
  653. public function wrap(\Closure $closure)
  654. {
  655. $this->wrapper = $closure;
  656. return $this;
  657. }
  658. /**
  659. * @return bool
  660. */
  661. public function hasWrapper()
  662. {
  663. return $this->wrapper ? true : false;
  664. }
  665. /**
  666. * Add variables to grid view.
  667. *
  668. * @param array $variables
  669. *
  670. * @return $this
  671. */
  672. public function with($variables = [])
  673. {
  674. $this->variables = $variables;
  675. return $this;
  676. }
  677. /**
  678. * Get all variables will used in grid view.
  679. *
  680. * @return array
  681. */
  682. protected function variables()
  683. {
  684. $this->variables['grid'] = $this;
  685. $this->variables['tableId'] = $this->getTableId();
  686. return $this->variables;
  687. }
  688. /**
  689. * Set a view to render.
  690. *
  691. * @param string $view
  692. * @param array $variables
  693. */
  694. public function view($view, $variables = [])
  695. {
  696. if (! empty($variables)) {
  697. $this->with($variables);
  698. }
  699. $this->view = $view;
  700. }
  701. /**
  702. * Set grid title.
  703. *
  704. * @param string $title
  705. *
  706. * @return $this
  707. */
  708. public function title($title)
  709. {
  710. $this->variables['title'] = $title;
  711. return $this;
  712. }
  713. /**
  714. * Set grid description.
  715. *
  716. * @param string $description
  717. *
  718. * @return $this
  719. */
  720. public function description($description)
  721. {
  722. $this->variables['description'] = $description;
  723. return $this;
  724. }
  725. /**
  726. * Set resource path for grid.
  727. *
  728. * @param string $path
  729. *
  730. * @return $this
  731. */
  732. public function setResource($path)
  733. {
  734. $this->resourcePath = $path;
  735. return $this;
  736. }
  737. /**
  738. * Get the string contents of the grid view.
  739. *
  740. * @return string
  741. */
  742. public function render()
  743. {
  744. $this->handleExportRequest();
  745. try {
  746. $this->callComposing();
  747. $this->build();
  748. } catch (\Throwable $e) {
  749. return Admin::makeExceptionHandler()->renderException($e);
  750. }
  751. return $this->doWrap();
  752. }
  753. /**
  754. * @return string
  755. */
  756. protected function doWrap()
  757. {
  758. $view = view($this->view, $this->variables());
  759. if (! $wrapper = $this->wrapper) {
  760. return $view->render();
  761. }
  762. return $wrapper($view);
  763. }
  764. /**
  765. * Add column to grid.
  766. *
  767. * @param string $name
  768. *
  769. * @return Column
  770. */
  771. public function __get($name)
  772. {
  773. return $this->addColumn($name);
  774. }
  775. /**
  776. * Dynamically add columns to the grid view.
  777. *
  778. * @param $method
  779. * @param $arguments
  780. *
  781. * @return Column
  782. */
  783. public function __call($method, $arguments)
  784. {
  785. if (static::hasMacro($method)) {
  786. return $this->macroCall($method, $arguments);
  787. }
  788. return $this->addColumn($method, $arguments[0] ?? null);
  789. }
  790. }