Select.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. _method: 'PUT'
  41. },
  42. reload = '{$refresh}';
  43. if (name.indexOf('.') === -1) {
  44. data[name] = value;
  45. } else {
  46. name = name.split('.');
  47. data[name[0]] = {};
  48. data[name[0]][name[1]] = value;
  49. }
  50. Dcat.NP.start();
  51. $.ajax({
  52. url: url,
  53. type: "POST",
  54. data: data,
  55. success: function (data) {
  56. Dcat.NP.done();
  57. Dcat.success(data.message);
  58. reload && Dcat.reload();
  59. }
  60. });
  61. });
  62. JS;
  63. Admin::script($script);
  64. }
  65. }