AsyncTable.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace Dcat\Admin\Widgets;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Grid\LazyRenderable;
  5. use Dcat\Admin\Traits\AsyncRenderable;
  6. use Illuminate\Support\Str;
  7. class AsyncTable extends Widget
  8. {
  9. use AsyncRenderable;
  10. public static $js = [
  11. '@grid-extension',
  12. ];
  13. protected $load = true;
  14. public function __construct(LazyRenderable $renderable = null, bool $load = true)
  15. {
  16. $this->setRenderable($renderable);
  17. $this->load($load);
  18. $this->id('table-card-'.Str::random(8));
  19. $this->class('table-card');
  20. }
  21. /**
  22. * 设置是否自动加载.
  23. *
  24. * @param bool $value
  25. *
  26. * @return $this
  27. */
  28. public function load(bool $value)
  29. {
  30. $this->load = $value;
  31. return $this;
  32. }
  33. /**
  34. * 监听异步渲染完成事件.
  35. *
  36. * @param string $script
  37. *
  38. * @return $this
  39. */
  40. public function onLoad(string $script)
  41. {
  42. $this->script .= "$(replaceNestedFormIndex('{$this->getElementSelector()}')).on('table:loaded', function (event) { {$script} });";
  43. return $this;
  44. }
  45. protected function addScript()
  46. {
  47. Admin::script(<<<'JS'
  48. Dcat.grid.AsyncTable('.table-card');
  49. JS
  50. );
  51. if ($this->load) {
  52. $this->script .= $this->getLoadScript();
  53. }
  54. }
  55. /**
  56. * @return string
  57. */
  58. public function getElementSelector()
  59. {
  60. return '#'.$this->getHtmlAttribute('id');
  61. }
  62. /**
  63. * @return string
  64. */
  65. public function getLoadScript()
  66. {
  67. return <<<JS
  68. $(replaceNestedFormIndex('{$this->getElementSelector()}')).trigger('table:load');
  69. JS;
  70. }
  71. public function render()
  72. {
  73. $this->addScript();
  74. return parent::render();
  75. }
  76. public function html()
  77. {
  78. $this->setHtmlAttribute([
  79. 'data-url' => $this->getRequestUrl(),
  80. ]);
  81. return <<<HTML
  82. <div {$this->formatHtmlAttributes()} style="min-height: 200px"></div>
  83. HTML;
  84. }
  85. }