Select.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 = [])
  10. {
  11. if ($options instanceof \Closure) {
  12. $options = $options->call($this, $this->row);
  13. }
  14. $this->addScript();
  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->resource()}" data-key="{$this->getKey()}" data-name="{$this->column->getName()}">
  23. $optionsHtml
  24. </select>
  25. </div>
  26. EOT;
  27. }
  28. protected function addScript()
  29. {
  30. $script = <<<JS
  31. $('.{$this->selector}').off('change').select2().on('change', function(){
  32. var pk = $(this).data('key'),
  33. value = $(this).val(),
  34. name = $(this).data('name'),
  35. url = $(this).data('url') + '/' + pk,
  36. data = {
  37. _token: Dcat.token,
  38. _method: 'PUT'
  39. };
  40. if (name.indexOf('.') === -1) {
  41. data[name] = value;
  42. } else {
  43. name = name.split('.');
  44. data[name[0]] = {};
  45. data[name[0]][name[1]] = value;
  46. }
  47. Dcat.NP.start();
  48. $.ajax({
  49. url: url,
  50. type: "POST",
  51. data: data,
  52. success: function (data) {
  53. Dcat.NP.done();
  54. Dcat.success(data.message);
  55. }
  56. });
  57. });
  58. JS;
  59. Admin::script($script);
  60. }
  61. }