I’ve done some research trying to determine the best way to programatically select an option on a select2 instance that uses an ajax data source. I know there’s already a doc at https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 here, however that doesn’t apply to my use case. My select2 is defined as follows:
$('#select_elm').select2({
ajax: {
transport: function(params, success, failure) {
CompanyLib.ajaxWrapper({
url: '/book/search',
data: params.data,
success: success,
error: failure
});
},
delay: 250,
data: function(params) {
return {
onlyReleased: true,
term: params.term,
page: params.page
}
},
processResults: function (data, page) {
return {
results: data.items
}
},
cache: true,
},
minimumInputLength: 3,
escapeMarkup: function (markup) { return markup; },
templateResult: function (result) {
if (result.loading) return result.text + ' <i class=\"pull-right icon-ajax\"></i>';
var returnHtml = CompanyLib.createStamp({
type: 'book',
icon: CompanyLib.icons.book,
stampLeft: result.bookStem,
stampRight: result.title
});
return returnHtml;
},
templateSelection: function (result) {
var returnHtml = CompanyLib.createStamp({
type: 'book',
icon: CompanyLib.icons.book,
stampLeft: result.bookStem,
stampRight: result.title
});
return returnHtml;
}
});
What I’m running into is that I will know the JSON payload separately from having select2 perform it’s own AJAX request, therefore there should be a way to just programatically call select2 and tell it to use that payload, just as if someone had selected it from the ajax sourced list. The select2 documentation contains an example of using a specific separate ajax request to get the data, and then parse out that data to 1), create an HTML5 option element using a speicific text & id reference, then append that to the original select element, and then 2) Trigger the ‘select2:select’ event on the element, to notify select2 that the options of changed.
This seems overcomplicated, as select2 already has logic within it to set the option element on the original select element it’s attached to (otherwise select2 via ajax wouldn’t work at all), so we shouldn’t need to separately create an Option element.
I did some digging, and found that calling $('#select_elm').data('select2').dataAdapter.select(jsonPayload);
performs what I was looking for. It takes the jsonPayload and processes it just as if someone had selected it from the dropdown list of ajax sourced data, both running the payload through the templateSelection
and setting the option/val on the original select element.
My question is there anything I’m missing that would be detrimental to using the dataAdapter this way? And as a followup, is there any reason this couldn’t be made a top-level command of $(#select_elm').select2('val', jsonPayload);
, since this is the only way I can see that properly accounts for templates in use on the select2 element.