FilterButton.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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->grid->getFilter();
  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()->getFilterID();
  40. Admin::script(<<<JS
  41. $('.{$this->getElementClassName()}').click(function(){
  42. $('#{$id}').parent().collapse('toggle');
  43. });
  44. JS
  45. );
  46. }
  47. /**
  48. * @return mixed
  49. */
  50. protected function renderScopes()
  51. {
  52. return $this->filter()->getScopes()->map->render()->implode("\r\n");
  53. }
  54. /**
  55. * Get label of current scope.
  56. *
  57. * @return string
  58. */
  59. protected function getCurrentScopeLabel()
  60. {
  61. if ($scope = $this->filter()->getCurrentScope()) {
  62. return "&nbsp;{$scope->getLabel()}&nbsp;";
  63. }
  64. return '';
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function render()
  70. {
  71. $filter = $this->filter();
  72. $scopres = $filter->getScopes();
  73. $filters = $filter->filters();
  74. if ($scopres->isEmpty() && !$filters) {
  75. return;
  76. }
  77. $this->setupScripts();
  78. $variables = [
  79. 'scopes' => $scopres,
  80. 'current_label' => $this->getCurrentScopeLabel(),
  81. 'url_no_scopes' => $filter->urlWithoutScopes(),
  82. 'btn_class' => $this->getElementClassName(),
  83. 'expand' => $filter->expand,
  84. 'show_filter_text' => true,
  85. ];
  86. return view($this->view, $variables)->render();
  87. }
  88. }