Select2

Select2

pcsintjanbaptistpcsintjanbaptist Posts: 20Questions: 9Answers: 1

Situation:
- I have a Datatable with its own Editor.
- This editor has a select-field "producttype" which triggers a dependent select-field "productsList".
- The list feeded into the field "productsList" is too long and becomes unreadable because of it.
- So I would like to add option groups
- I found this question in which Allan says: "This is the format (ID/text) select2 expects, and editor needs value/label, so you'll need to convert it."
- I managed to provide the ajax-result in the necessary format, but I can't seem to figure out how to tell the editor to just use the select2 format instead of the editor format.

So my question is now: am I supposed to use the "optionsPair"-attribute to convert the feeded ajax-result myself or is there a way I can tell the editor to use the select2 format?

Thanks in advance,

Gloria

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,488Questions: 1Answers: 10,467 Site admin
    Answer ✓

    Hi Gloria,

    Using the build in methods (e.g. field().update()) there is no way to use the option groups available with Select2.

    What I think you would need to do is bypass the field().update() method (which I presume you are using at the moment?) and work with the Select2 API directly.

    You can work with the Select2 API by using the field().inst() method that the Select2 plug-in for Editor exposes - e.g.:

    editor.field('productsList').inst('open');
    

    would open the select2 instance (https://select2.org/programmatic-control/methods).

    Looking at their API it doesn't look quite so trivial to add option group options though. You'd need to manipulate the select element directly (which is what we do in the plug-in when adding options as well).

    Use editor.field('productsList').input() to get a reference to the select element. Then delete all of the options, add your new ones and finally trigger a change event to let Select2 know that it should update:

    let select = editor.field('productsList').input();
    
    select[0].options.length = 0;
    
    // Create new options and option groups appending to `select`
    // ...
    
    select.trigger('change');
    

    It'd be so much easier if they just had an API method that let you feed in your list of options. Perhaps that is there somewhere, but I'm not seeing it in their docs!

    Allan

This discussion has been closed.