Select2 does not know the corresponding text of selected value
Asked Answered
R

3

6

I use remote data source for options. When I load form data from server, it only contains the values of select elements. In such situation, select2 does not know the corresponding text to show to user. Is there any built-in reusable mechanism for this common scenario?

How to set the currently selected value/text when data are fetched using ajax?

$('select#test').select2({
                    ajax: {
                        url: "user/combo",
                        dataType: 'json',
                        delay: 250,
                        cache: true
                    }
                });
            }
        }

Indeed, I am trying to create an angular directive as follow:

app.directive('mehrUserCombo', ['$http', function ($http) {
        return {
            link: function (scope, element, attr) {
                element.select2({
                    ajax: {
                        url: "user/combo",
                        dataType: 'json',
                        delay: 250,
                        cache: true
                    }
                });
            }
        }
Reactor answered 12/5, 2015 at 1:2 Comment(0)
Q
6

These are your ajax options :

ajax: {
  // The number of milliseconds to wait for the user to stop typing before
  // issuing the ajax request.
  delay: 250,
  // You can craft a custom url based on the parameters that are passed into the
  // request. This is useful if you are using a framework which has
  // JavaScript-based functions for generating the urls to make requests to.
  //
  // @param params The object containing the parameters used to generate the
  //   request.
  // @returns The url that the request should be made to.
  url: function(params) {
    return UrlGenerator.Random();
  },
  // You can pass custom data into the request based on the parameters used to
  // make the request. For `GET` requests, the default method, these are the
  // query parameters that are appended to the url. For `POST` requests, this
  // is the form data that will be passed into the request. For other requests,
  // the data returned from here should be customized based on what jQuery and
  // your server are expecting.
  //
  // @param params The object containing the parameters used to generate the
  //   request.
  // @returns Data to be directly passed into the request.
  data: function(params) {
    var queryParameters = {
      q: params.term
    }

    return queryParameters;
  },
  // You can modify the results that are returned from the server, allowing you
  // to make last-minute changes to the data, or find the correct part of the
  // response to pass to Select2. Keep in mind that results should be passed as
  // an array of objects.
  //
  // @param data The data as it is returned directly by jQuery.
  // @returns An object containing the results data as well as any required
  //   metadata that is used by plugins. The object should contain an array of
  //   data objects as the `results` key.
  processResults: function(data) {
    return {
      results: data
    };
  },
  // You can use a custom AJAX transport function if you do not want to use the
  // default one provided by jQuery.
  //
  // @param params The object containing the parameters used to generate the
  //   request.
  // @param success A callback function that takes `data`, the results from the
  //   request.
  // @param failure A callback function that indicates that the request could
  //   not be completed.
  // @returns An object that has an `abort` function that can be called to abort
  //   the request if needed.
  transport: function(params, success, failure) {
    var $request = $.ajax(params);

    $request.then(success);
    $request.fail(failure);

    return $request;
  }
}

on the processResult function use :

 processResults: function(data) {
   $('select#test').select2("val", YOUR VALUE FROM PROCESSED DATA); //set the value
   return {
     results: data
   };
 }
Quizmaster answered 16/5, 2015 at 3:49 Comment(0)
M
1

You can use the data & results functions within your ajax call to request, parse, and set your json data dependent on your data.

Here's a small code snippet from some of my production code that does something similar to what you're asking:

$(".autocomplete-search").select2({
  placeholder: "Pizza, Movies, etc...",
  minimumInputLength: 2,
  ajax: {
    url: '/find-suggestions.json',
    dataType: 'json',
    quietMillis: 250,
    data: function(params, page) {
      return {
        query: params,
        page: page
      };
    },
    results: function(data, page) {
      var more, search_all, searched_for;
      searched_for = $(".select2-search input").val();
      search_all = [
        {
          query: searched_for
        }
      ];
      more = data.suggestions.stores.length >= 1;
      return {
        results: search_all.concat(data.suggestions.categories, data.suggestions.stores),
        more: more
      };
    }
  }
});

In data: I'm using the params value to pass the original value to my ajax api, then in the results: returning the data; I can get the original input value (searched_for) and pair it with other data below, parsing it out and concatenating it as seen in the example.

I don't know how to give you the exact answer you are looking for without more detail, but I believe the code snippet illustrates the types of behaviors you are trying to accomplish. Also, I just noticed @prollyGeek's answer came through as I was typing this, read the docs in the comments as well, quite helpful.

Mandel answered 16/5, 2015 at 4:0 Comment(1)
@PHPst, I think you need to show some code (e.g. what does your option list look like, and where are you trying to stick it - maybe use jsfiddle/codepen). It's still quite vague. You are trying to show only what they selected? or show some data coming from an external source?Mandel
C
1

You could just check this angular module wrapping select2 into angular in a proper way : ui-select Since it use angular binding. You should be able to set a value return after the promise resolve. Anyway you shouldn't use the ajax() function and use $http instead for all your asynchronous calls.

Here is an exemple :

<ui-select ng-model="person.selected" theme="select2" ng-disabled="disabled" style="min-width: 300px;">
    <ui-select-match placeholder="Select a person in the list or search his name/age...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">
      <div ng-bind-html="person.name | highlight: $select.search"></div>
      <small>
        email: {{person.email}}
        age: <span ng-bind-html="''+person.age | highlight: $select.search"></span>
      </small>
    </ui-select-choices>
  </ui-select>

Your binded value in the exemple is "person.selected" and the list is "people" You just have to do something like this in your controller :

$http.get("/yourdatauri").success(function(data){
  $scope.people = data;
});

Hope it'll help you out.

Colophony answered 20/5, 2015 at 0:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.