Grid.php 19 KB

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