SwitchDisplay.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace Dcat\Admin\Grid\Displayers;
  3. use Dcat\Admin\Admin;
  4. class SwitchDisplay extends AbstractDisplayer
  5. {
  6. public static $js = '@switchery';
  7. public static $css = '@switchery';
  8. protected $selector = 'grid-column-switch';
  9. /**
  10. * @var string
  11. */
  12. protected $color;
  13. public function color($color)
  14. {
  15. $this->color = Admin::color()->get($color);
  16. }
  17. public function display(string $color = '', $refresh = false)
  18. {
  19. if ($color instanceof \Closure) {
  20. $color->call($this->row, $this);
  21. } else {
  22. $this->color($color);
  23. }
  24. $this->addScript($refresh);
  25. $checked = $this->value ? 'checked' : '';
  26. $color = $this->color ?: Admin::color()->primary();
  27. return <<<EOF
  28. <input class="{$this->selector}" data-url="{$this->url()}" data-size="small" name="{$this->column->getName()}" {$checked} type="checkbox" data-color="{$color}"/>
  29. EOF;
  30. }
  31. protected function url()
  32. {
  33. return $this->resource().'/'.$this->getKey();
  34. }
  35. protected function addScript($refresh)
  36. {
  37. Admin::script(
  38. <<<JS
  39. (function() {
  40. var swt = $('.{$this->selector}'),
  41. that,
  42. reload = '{$refresh}';
  43. function initSwitchery(){
  44. swt.parent().find('.switchery').remove();
  45. swt.each(function(k){
  46. that = $(this);
  47. new Switchery(that[0], that.data())
  48. })
  49. }
  50. initSwitchery();
  51. swt.off('change').change(function(e) {
  52. var that = $(this),
  53. url = that.data('url'),
  54. checked = that.is(':checked'),
  55. name = that.attr('name'),
  56. data = {
  57. _method: 'PUT'
  58. },
  59. value = checked ? 1 : 0;
  60. if (name.indexOf('.') === -1) {
  61. data[name] = value;
  62. } else {
  63. name = name.split('.');
  64. data[name[0]] = {};
  65. data[name[0]][name[1]] = value;
  66. }
  67. Dcat.NP.start();
  68. $.ajax({
  69. url: url,
  70. type: "POST",
  71. data: data,
  72. success: function (d) {
  73. Dcat.NP.done();
  74. if (d.status) {
  75. Dcat.success(d.message);
  76. reload && Dcat.reload();
  77. } else {
  78. Dcat.error(d.message);
  79. }
  80. }
  81. });
  82. });
  83. })();
  84. JS
  85. );
  86. }
  87. }