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