SwitchGroup.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Dcat\Admin\Grid\Displayers;
  3. use Dcat\Admin\Admin;
  4. use Illuminate\Support\Arr;
  5. class SwitchGroup extends SwitchDisplay
  6. {
  7. protected $selector = 'grid-column-switch-group';
  8. public function display($columns = [], $color = '', $refresh = false)
  9. {
  10. if ($columns instanceof \Closure) {
  11. $columns = $columns->call($this->row, $this);
  12. }
  13. $this->addScript($refresh);
  14. if ($color) {
  15. $this->color($color);
  16. }
  17. if (! Arr::isAssoc($columns)) {
  18. $labels = array_map('admin_trans_field', $columns);
  19. $columns = array_combine($columns, $labels);
  20. }
  21. $html = [];
  22. foreach ($columns as $column => $label) {
  23. $html[] = $this->buildSwitch($column, $label);
  24. }
  25. return '<table>'.implode('', $html).'</table>';
  26. }
  27. protected function buildSwitch($name, $label = '')
  28. {
  29. $checked = Arr::get($this->row->toArray(), $name) ? 'checked' : '';
  30. $color = $this->color ?: Admin::color()->primary();
  31. return <<<EOT
  32. <tr style="box-shadow: none;background: transparent">
  33. <td style="padding: 3px 0;height:23px;">{$label}:&nbsp;&nbsp;&nbsp;</td>
  34. <td style="padding: 3px 0;height:23px;"><input name="{$name}" data-path="{$this->resource()}" data-key="{$this->getKey()}" $checked
  35. type="checkbox" class="{$this->selector}" data-size="small" data-color="{$color}"/></td>
  36. </tr>
  37. EOT;
  38. }
  39. protected function addScript($refresh)
  40. {
  41. $script = <<<JS
  42. (function () {
  43. var swt = $('.{$this->selector}'),
  44. reload = '{$refresh}',
  45. that;
  46. function initSwitchery() {
  47. swt.each(function() {
  48. that = $(this);
  49. that.parent().find('.switchery').remove();
  50. new Switchery(that[0], that.data())
  51. })
  52. }
  53. initSwitchery();
  54. swt.off('change').change(function(e) {
  55. var that = $(this),
  56. id = that.data('key'),
  57. url = that.data('path') + '/' + id,
  58. checked = that.is(':checked'),
  59. name = that.attr('name'),
  60. data = {
  61. _token: Dcat.token,
  62. _method: 'PUT'
  63. },
  64. value = checked ? 1 : 0;
  65. if (name.indexOf('.') === -1) {
  66. data[name] = value;
  67. } else {
  68. name = name.split('.');
  69. data[name[0]] = {};
  70. data[name[0]][name[1]] = value;
  71. }
  72. Dcat.NP.start();
  73. $.ajax({
  74. url: url,
  75. type: "POST",
  76. data: data,
  77. success: function (d) {
  78. Dcat.NP.done();
  79. if (d.status) {
  80. Dcat.success(d.message);
  81. reload && Dcat.reload()
  82. } else {
  83. Dcat.error(d.message);
  84. }
  85. }
  86. });
  87. });
  88. })();
  89. JS;
  90. Admin::script($script);
  91. }
  92. }