SwitchField.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Form\Field;
  5. class SwitchField extends Field
  6. {
  7. public function primary()
  8. {
  9. return $this->color('var(--primary)');
  10. }
  11. public function green()
  12. {
  13. return $this->color('var(--success)');
  14. }
  15. public function custom()
  16. {
  17. return $this->color('var(--custom)');
  18. }
  19. public function yellow()
  20. {
  21. return $this->color('var(--warning)');
  22. }
  23. public function red()
  24. {
  25. return $this->color('var(--danger)');
  26. }
  27. public function purple()
  28. {
  29. return $this->color('var(--purple)');
  30. }
  31. public function blue()
  32. {
  33. return $this->color('var(--blue)');
  34. }
  35. /**
  36. * Set color of the switcher.
  37. *
  38. * @param $color
  39. * @return $this
  40. */
  41. public function color($color)
  42. {
  43. return $this->attribute('data-color', $color);
  44. }
  45. /**
  46. *
  47. * @param $color
  48. * @return $this
  49. */
  50. public function secondary($color)
  51. {
  52. return $this->attribute('data-secondary-color', $color);
  53. }
  54. /**
  55. * @return $this
  56. */
  57. public function small()
  58. {
  59. return $this->attribute('data-size', 'small');
  60. }
  61. /**
  62. * @return $this
  63. */
  64. public function large()
  65. {
  66. return $this->attribute('data-size', 'large');
  67. }
  68. /**
  69. * @param mixed $value
  70. * @return int
  71. */
  72. protected function prepareToSave($value)
  73. {
  74. return $value ? 1 : 0;
  75. }
  76. public function render()
  77. {
  78. if (empty($this->attributes['data-size'])) {
  79. $this->small();
  80. }
  81. if (empty($this->attributes['data-color'])) {
  82. $this->primary();
  83. }
  84. $this->attribute('name', $this->getElementName());
  85. $this->attribute('value', 1);
  86. $this->attribute('type', 'checkbox');
  87. $this->attribute('data-plugin', $this->getFormId().'switchery');
  88. Admin::script(<<<JS
  89. function swty(){\$('[data-plugin="{$this->getFormId()}switchery"]').each(function(){new Switchery($(this)[0],$(this).data())})} swty();
  90. JS
  91. );
  92. return parent::render();
  93. }
  94. public static function collectAssets()
  95. {
  96. Admin::collectComponentAssets('switchery');
  97. }
  98. }