The select2 is almost working how I want it. It loads all the remote data and formats its correctly when another field is changed. I want to add back in the search function on the retrieved data i.e. once the data is retrieved, the user can search the list by the title (result.title).
In the example below, the data is retrieved, but the search term is not being filtered. It is important that all the remote data be loaded first before the user has to search for a result.
If I cant add the ability to search, how do I disable the search box? If I set "minimumResultsForSearch: -1", the select2 box still lets me search?
var $company2 = $(".company2");
$company2.select2().on('change', function() {
if ($company2.val() !== null) {
$('.unmaintained2').select2({
allowClear: true,
minimumResultsForSearch: 1,
ajax: {
url: "/api/unmaintained2/" + $company2.val(),
processResults: function (data) {
return {
results: data,
};
},
dataType: 'json',
cache: true,
},
escapeMarkup: function(m) {
return m;
},
templateResult: function (result) {
if (result.loading) return 'Loading...';
return result.text + '<h6>' + result.make + ' ' + result.category + '</h6>';
},
});
};
});
Thanks to @dns_nx below is the final solution! The select2 is now searchable (client side) and templatable with remote data!
$(document).ready(function() {
var $company2 = $(".company2");
var $equipment2 = $(".equipment2");
$company2.select2().on('change', function() {
$equipment2.empty();
if ($company2.val() !== null) {
$.ajax({
url: "{{ url('/') }}" + "/api/unmaintained2/" + $company2.val(),
type: 'GET',
dataType: 'json',
async: true,
success: function(data) {
$equipment2.select2({
data: data,
templateSelection: function(result) {
return result.text;
},
templateResult: function(result) {
if (!result.id) {
return result.text;
}
var final = '<h2>'+ result.serial + '</h2><h5>(' + result.make + ') ' + result.category + '</h5>';
return final;
},
escapeMarkup: function(result) {
return result;
},
});
}
});
}
}).trigger('change');
});