Checkbox.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Support\Helper;
  4. use Dcat\Admin\Widgets\Checkbox as WidgetCheckbox;
  5. class Checkbox extends MultipleSelect
  6. {
  7. use CanCascadeFields;
  8. use CanLoadFields;
  9. protected $style = 'primary';
  10. protected $cascadeEvent = 'change';
  11. protected $canCheckAll = false;
  12. protected $inline = true;
  13. /**
  14. * @param array|\Closure|string $options
  15. *
  16. * @return $this|mixed
  17. */
  18. public function options($options = [])
  19. {
  20. if ($options instanceof \Closure) {
  21. $this->options = $options;
  22. return $this;
  23. }
  24. $this->options = Helper::array($options);
  25. return $this;
  26. }
  27. /**
  28. * "info", "primary", "inverse", "danger", "success", "purple".
  29. *
  30. * @param string $style
  31. *
  32. * @return $this
  33. */
  34. public function style(string $style)
  35. {
  36. $this->style = $style;
  37. return $this;
  38. }
  39. /**
  40. * Add a checkbox above this component, so you can select all checkboxes by click on it.
  41. *
  42. * @return $this
  43. */
  44. public function canCheckAll()
  45. {
  46. $this->canCheckAll = true;
  47. return $this;
  48. }
  49. public function inline(bool $inline)
  50. {
  51. $this->inline = $inline;
  52. return $this;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function render()
  58. {
  59. if ($this->options instanceof \Closure) {
  60. $this->options(
  61. $this->options->call($this->values(), $this->value(), $this)
  62. );
  63. }
  64. $this->addCascadeScript();
  65. $checkbox = WidgetCheckbox::make(
  66. $this->getElementName().'[]',
  67. $this->options,
  68. $this->style
  69. );
  70. if ($this->attributes['disabled'] ?? false) {
  71. $checkbox->disable();
  72. }
  73. $checkbox
  74. ->inline($this->inline)
  75. ->check($this->value())
  76. ->class($this->getElementClassString())
  77. ->size($this->size);
  78. $this->addVariables([
  79. 'checkbox' => $checkbox,
  80. 'checkAll' => $this->makeCheckAllCheckbox(),
  81. ]);
  82. return parent::render();
  83. }
  84. protected function makeCheckAllCheckbox()
  85. {
  86. if (! $this->canCheckAll) {
  87. return;
  88. }
  89. $this->addVariables(['canCheckAll' => $this->canCheckAll]);
  90. return WidgetCheckbox::make('_check_all_', [__('admin.all')]);
  91. }
  92. }