AbstractTool.php 2.0 KB

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