Preselect data for select2 combobox multiple when source comes from Ajax is not working

Hello,

when select2 data comes from Ajax source and the combobox is configured for single value, I just create an HTML SELECT with only one option (the selected one) and the Select2 combobox appears initially with that option selected, even when the ajax source was not called yet. If I expand the combobox, the Ajax source is called and all options are retrieved with the original option marked as selected.

So far, so good. That does not work when Select2 is configured as multiple selection.

Even when I initialize the HTML SELECT with a selected option, that option does not appear initially selected.

This is the HTML SELECT after Select2 is applied:

<select class="form-control select2-hidden-accessible" data-val="true" data-val-range="Debe indicar el Rol del usuario." data-val-range-max="2147483647" data-val-range-min="1" id="Roles" multiple="" name="Roles" required="required" style="width: 100%" data-select2-id="Roles" tabindex="-1" aria-hidden="true">
    <option value="1" data-select2-id="5">Administrador</option>
</select>

As you see, Select2 added a data-select2-id attribute to the option element, but even when Select2 knows the option is there, it does not appear in the generated UL list.

If I expand the combobox and select other item, the HTML SELECT becomes this way:

<select class="form-control select2-hidden-accessible" data-val="true" data-val-range="Debe indicar el Rol del usuario." data-val-range-max="2147483647" data-val-range-min="1" id="Roles" multiple="" name="Roles" required="required" style="width: 100%" data-select2-id="Roles" tabindex="-1" aria-hidden="true">
    <option value="1" data-select2-id="5">Administrador</option>
    <option value="5" data-select2-id="20">Empleador</option>
</select>

Why the default option is not added in the UL list?

If I select the default option in the list, it is not added again in the HTML SELECT (because Select2 takes care there is already that option) but it is added to the UL list as a LI item.

Any help, please?

Regards

Jaime

The Select2 documentation has information about this situation: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2