BatchActions.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Dcat\Admin\Grid\Tools;
  3. use Dcat\Admin\Admin;
  4. use Illuminate\Support\Collection;
  5. class BatchActions extends AbstractTool
  6. {
  7. /**
  8. * @var Collection
  9. */
  10. protected $actions;
  11. /**
  12. * @var bool
  13. */
  14. protected $enableDelete = true;
  15. /**
  16. * BatchActions constructor.
  17. */
  18. public function __construct()
  19. {
  20. $this->actions = new Collection();
  21. $this->appendDefaultAction();
  22. }
  23. /**
  24. * Append default action(batch delete action).
  25. *
  26. * return void
  27. */
  28. protected function appendDefaultAction()
  29. {
  30. $this->add(new BatchDelete(trans('admin.delete')));
  31. }
  32. /**
  33. * Disable delete.
  34. *
  35. * @return $this
  36. */
  37. public function disableDelete(bool $disable = true)
  38. {
  39. $this->enableDelete = !$disable;
  40. return $this;
  41. }
  42. /**
  43. * Add a batch action.
  44. *
  45. * @param BatchAction $action
  46. *
  47. * @return $this
  48. */
  49. public function add(BatchAction $action)
  50. {
  51. $id = $this->actions->count();
  52. $action->setId($id);
  53. $this->actions->push($action);
  54. return $this;
  55. }
  56. /**
  57. * Setup scripts of batch actions.
  58. *
  59. * @return void
  60. */
  61. protected function setUpScripts()
  62. {
  63. foreach ($this->actions as $action) {
  64. $action->setGrid($this->grid);
  65. Admin::script($action->script());
  66. }
  67. }
  68. /**
  69. * Render BatchActions button groups.
  70. *
  71. * @return string
  72. */
  73. public function render()
  74. {
  75. if (!$this->enableDelete) {
  76. $this->actions->shift();
  77. }
  78. if ($this->actions->isEmpty()) {
  79. return '';
  80. }
  81. $this->setUpScripts();
  82. $data = [
  83. 'actions' => $this->actions,
  84. ];
  85. return view('admin::grid.batch-actions', $data)->render();
  86. }
  87. }