SwitchGroup.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. public function display($columns = [], string $color = '')
  8. {
  9. if ($columns instanceof \Closure) {
  10. $columns = $columns->call($this->row, $this);
  11. }
  12. if ($color) {
  13. $this->color($color);
  14. }
  15. if (! Arr::isAssoc($columns)) {
  16. $labels = array_map('admin_trans_field', $columns);
  17. $columns = array_combine($columns, $labels);
  18. }
  19. $html = [];
  20. foreach ($columns as $column => $label) {
  21. $html[] = $this->buildSwitch($column, $label);
  22. }
  23. return '<table>'.implode('', $html).'</table>';
  24. }
  25. protected function buildSwitch($name, $label = '')
  26. {
  27. $class = 'grid-switch-group-'.$this->grid->getName();
  28. $keys = collect(explode('.', $name));
  29. if ($keys->isEmpty()) {
  30. $elementName = $name;
  31. } else {
  32. $elementName = $keys->shift().$keys->reduce(function ($carry, $val) {
  33. return "{$carry}[{$val}]";
  34. });
  35. }
  36. $script = <<<JS
  37. (function () {
  38. var swt = $('.$class'), t;
  39. function init(){
  40. swt.each(function(){
  41. t = $(this);
  42. t.parent().find('.switchery').remove();
  43. new Switchery(t[0], t.data())
  44. })
  45. }
  46. init();
  47. swt.off('change').change(function(e) {
  48. var t = $(this),
  49. id = t.data('key'),
  50. checked = t.is(':checked'),
  51. name = t.attr('name'),
  52. data = {
  53. _token: Dcat.token,
  54. _method: 'PUT'
  55. };
  56. data[name] = checked ? 1 : 0;
  57. Dcat.NP.start();
  58. $.ajax({
  59. url: "{$this->resource()}/" + id,
  60. type: "POST",
  61. data: data,
  62. success: function (d) {
  63. Dcat.NP.done();
  64. if (d.status) {
  65. Dcat.success(d.message);
  66. } else {
  67. Dcat.error(d.message);
  68. }
  69. }
  70. });
  71. });
  72. })();
  73. JS;
  74. Admin::script($script);
  75. $key = $this->getKey();
  76. $checked = $this->row->$name ? 'checked' : '';
  77. $color = $this->color ?: Admin::color()->primary();
  78. return <<<EOT
  79. <tr style="box-shadow: none;background: transparent">
  80. <td style="padding: 3px 0;height:23px;">{$label}:&nbsp;&nbsp;&nbsp;</td>
  81. <td style="padding: 3px 0;height:23px;"><input name="{$elementName}" data-key="$key" $checked type="checkbox" class="$class" data-size="small" data-color="{$color}"/></td>
  82. </tr>
  83. EOT;
  84. }
  85. }