【问题标题】:Select2 Transform DataSelect2 转换数据
【发布时间】:2021-04-26 17:36:58
【问题描述】:

我有这样的数据。

kode explanation
082.B.2 Test1
083.B.3 Test2

这是我的功能:

       public function selectprogram(Request $req)
      {
        if ($req->ajax())
        {
          $search = $req->get('q');
          $page = $req->get('page');
          $resultCount = 10;
          $offset = ($page - 1) * $resultCount;
          $data = Refprogram::where('kode_program','LIKE','%'.$search .'%')
          ->orWhere('uraian','LIKE','%'.$search.'%')
          ->orderby('kode_program')
          ->skip($offset)
          ->take($resultCount)
          ->get(['kode_program',DB::raw("CONCAT(kode_program,' - ', uraian) AS text")]);
           $count = Refprogram::count();
           $endCount = $offset + $resultCount;
           $morePages = $endCount < $count;
           $results = array(
                "results" => $data,
                "pagination" => array(
                  "more" => $morePages
                )
              );
          return response()->json($results);
        }
      }

这是我的 JS Select2:

        $('#select2-program').select2({
            multiple:false,
            placeholder:'Please select one',
            allowClear: true,
            pagination:true,
            ajax : {
              method : 'get',
              url : '{{$breadcrumbs['select2_url_program']}}',
              data :function (params) {
                return {
                  q: params.term || '',
                  page: params.page || 1
                }
               
              },

              cache:true
            }
          });

我的问题是,我如何通过使用数字的 select2 更改或转换默认集 id 到文本。我想使用 kode 作为它的值,而不是 id(数字)。

【问题讨论】:

    标签: javascript php ajax laravel jquery-select2


    【解决方案1】:

    $('#mySelect2').select2({
      ajax: {
        url: '/example/api',
        processResults: function (data) {
          // Transforms the top-level key of the response object from 'items' to 'results'
          return {
            results: data.items
          };
        }
      }
    });

    https://select2.org/data-sources/ajax#transforming-response-data

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多