FilterButton.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace Dcat\Admin\Grid\Tools;
  3. use Dcat\Admin\Admin;
  4. use Illuminate\Support\Str;
  5. class FilterButton extends AbstractTool
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $view = 'admin::filter.button';
  11. /**
  12. * @var string
  13. */
  14. protected $btnClassName;
  15. /**
  16. * @return \Dcat\Admin\Grid\Filter
  17. */
  18. protected function filter()
  19. {
  20. return $this->parent->filter();
  21. }
  22. /**
  23. * Get button class name.
  24. *
  25. * @return string
  26. */
  27. protected function getElementClassName()
  28. {
  29. if (! $this->btnClassName) {
  30. $this->btnClassName = 'filter-btn-'.Str::random(8);
  31. }
  32. return $this->btnClassName;
  33. }
  34. /**
  35. * Set up script for filter button.
  36. */
  37. protected function setupScripts()
  38. {
  39. $id = $this->filter()->filterID();
  40. Admin::script(
  41. <<<JS
  42. $('.{$this->getElementClassName()}').click(function(){
  43. $('#{$id}').parent().collapse('toggle');
  44. });
  45. JS
  46. );
  47. }
  48. /**
  49. * @return mixed
  50. */
  51. protected function renderScopes()
  52. {
  53. return $this->filter()->scopes()->map->render()->implode("\r\n");
  54. }
  55. /**
  56. * Get label of current scope.
  57. *
  58. * @return string
  59. */
  60. protected function currentScopeLabel()
  61. {
  62. if ($scope = $this->filter()->currentScope()) {
  63. return "&nbsp;{$scope->getLabel()}&nbsp;";
  64. }
  65. return '';
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function render()
  71. {
  72. $filter = $this->filter();
  73. $scopres = $filter->scopes();
  74. $filters = $filter->filters();
  75. if ($scopres->isEmpty() && ! $filters) {
  76. return;
  77. }
  78. $this->setupScripts();
  79. $onlyScopes = ((! $filters || $this->parent->option('show_filter') === false) && ! $scopres->isEmpty()) ? true : false;
  80. $variables = [
  81. 'scopes' => $scopres,
  82. 'current_label' => $this->currentScopeLabel(),
  83. 'url_no_scopes' => $filter->urlWithoutScopes(),
  84. 'btn_class' => $this->getElementClassName(),
  85. 'expand' => $filter->expand,
  86. 'show_filter_text' => true,
  87. 'only_scopes' => $onlyScopes,
  88. ];
  89. return view($this->view, $variables)->render();
  90. }
  91. }