Select.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Dcat\Admin\Grid\Displayers;
  3. use Dcat\Admin\Admin;
  4. class Select extends AbstractDisplayer
  5. {
  6. public static $js = '@select2';
  7. public static $css = '@select2';
  8. protected $selector = 'grid-column-select';
  9. public function display($options = [], $refresh = false)
  10. {
  11. if ($options instanceof \Closure) {
  12. $options = $options->call($this, $this->row);
  13. }
  14. $this->addScript($refresh);
  15. $optionsHtml = '';
  16. foreach ($options as $option => $text) {
  17. $selected = (string) $option === (string) $this->value ? 'selected' : '';
  18. $optionsHtml .= "<option value=\"$option\" $selected>$text</option>";
  19. }
  20. return <<<EOT
  21. <div class="input-group input-group-sm">
  22. <select style="width: 100%;" class="{$this->selector}" data-url="{$this->url()}" data-name="{$this->column->getName()}">
  23. $optionsHtml
  24. </select>
  25. </div>
  26. EOT;
  27. }
  28. protected function url()
  29. {
  30. return $this->resource().'/'.$this->getKey();
  31. }
  32. protected function addScript($refresh)
  33. {
  34. $script = <<<JS
  35. $('.{$this->selector}').off('change').select2().on('change', function(){
  36. var value = $(this).val(),
  37. name = $(this).data('name'),
  38. url = $(this).data('url'),
  39. data = {
  40. _token: Dcat.token,
  41. _method: 'PUT'
  42. },
  43. reload = '{$refresh}';
  44. if (name.indexOf('.') === -1) {
  45. data[name] = value;
  46. } else {
  47. name = name.split('.');
  48. data[name[0]] = {};
  49. data[name[0]][name[1]] = value;
  50. }
  51. Dcat.NP.start();
  52. $.ajax({
  53. url: url,
  54. type: "POST",
  55. data: data,
  56. success: function (data) {
  57. Dcat.NP.done();
  58. Dcat.success(data.message);
  59. reload && Dcat.reload();
  60. }
  61. });
  62. });
  63. JS;
  64. Admin::script($script);
  65. }
  66. }