I'm using Select2 4.0.3 with remote data and server paging and it is working fine. The data returned from the api has additional fields, something like this:
var data = {
id: 12345,
text: 'John Doe',
email: 'abc@123.com'
}
According to the documentation here is the example of how to pre-select an option when using remote data, which also works fine (with one issue as noted below):
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
The documentation explains about the last bit:
Notice that we manually trigger the select2:select event and pass along the entire data object. This allows other handlers to access additional properties of the selected item.
In my case the additional property is the email field.
My question/problem is that for the above 'manually' appended option the select2 JSON data has only the id and text fields. If the user clicks the list and allows it to populate the data from the server then the data has the id, text, and email fields as it should.
The documentation statement explaining why the trigger was needed indicates to me that the data object returned from the api would be passed on (and presumably used), but this does not seem to be the case.
So in my case leaving out or including the trigger portion has no effect of the control, so am I misunderstanding the purpose of that code or is select2 not working as documented?
For Example, in the templateSelection function used to format the control selection, which is called when the append and trigger code is executed, the object passed to the function has only the id and text properties. In fact if the original data object had completely different properties, say name, value, and email, the data object passed to the function still has id and text only, which is the default object used by select2. This behaviour forced me to modify the object to conform to the {id, text} pattern.