AbstractTool.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Dcat\Admin\Actions\Action;
  4. use Dcat\Admin\Form;
  5. abstract class AbstractTool extends Action
  6. {
  7. /**
  8. * @var Form
  9. */
  10. protected $parent;
  11. /**
  12. * @var string
  13. */
  14. public $selectorPrefix = '.form-tool-action-';
  15. /**
  16. * @var string
  17. */
  18. protected $style = 'btn btn-sm btn-primary';
  19. /**
  20. * Whether the action should only allow in creation page.
  21. *
  22. * @var bool
  23. */
  24. public $allowOnlyCreating = false;
  25. /**
  26. * Whether the action should only allow in edit page.
  27. *
  28. * @var bool
  29. */
  30. public $allowOnlyEditing = false;
  31. /**
  32. * @param Form $form
  33. *
  34. * @return void
  35. */
  36. public function setForm(Form $form)
  37. {
  38. $this->parent = $form;
  39. }
  40. /**
  41. * @return array|mixed|string|null
  42. */
  43. public function key()
  44. {
  45. if ($this->primaryKey) {
  46. return $this->primaryKey;
  47. }
  48. return $this->parent ? $this->parent->key() : null;
  49. }
  50. /**
  51. * @return string
  52. */
  53. public function render()
  54. {
  55. if ($this->allowOnlyEditing && ! $this->parent->isEditing()) {
  56. return '';
  57. }
  58. if ($this->allowOnlyCreating && ! $this->parent->isCreating()) {
  59. return '';
  60. }
  61. return parent::render(); // TODO: Change the autogenerated stub
  62. }
  63. /**
  64. * @return void
  65. */
  66. public function setupHtmlAttributes()
  67. {
  68. $this->addHtmlClass($this->style);
  69. parent::setupHtmlAttributes();
  70. }
  71. /**
  72. * @param mixed ...$params
  73. *
  74. * @return $this
  75. */
  76. public static function allowOnlyCreating(...$params)
  77. {
  78. $tool = static::make(...$params);
  79. $tool->allowOnlyCreating = true;
  80. $tool->allowOnlyEditing = false;
  81. return $tool;
  82. }
  83. /**
  84. * @param mixed ...$params
  85. *
  86. * @return $this
  87. */
  88. public static function allowOnlyEditing(...$params)
  89. {
  90. $tool = static::make(...$params);
  91. $tool->allowOnlyEditing = true;
  92. $tool->allowOnlyCreating = false;
  93. return $tool;
  94. }
  95. }