using select2 I need to create and select new option
using select2 I need to create and select new option
I have an Events table and a Clients table on the server. From the Events Editor view there is a select2 pull down to select a Client. If <new> is selected, I switch forms to the Client Editor view and allow user to create the new Client row.
When I switch back to the Events Editor form, I need to update the select2 with the new Client, and have that new Client selected.
Commentary within https://editor.datatables.net/plug-ins/field-type/editor.select2 seems to indicate that this cannot be achieved directly within the javascript, that an ajax call is needed to update the options.
But it seems like field().update()
then field().set()
could be used. Having said that, it looks like update() requires the full option list to be configured, so I would need to access the current option list, add my new option using update(), then set the new value using val().
I think there isn't a method to get the current option list. Can I retrieve the current option list by accessing the select2 configuration? e.g., through conf._input[0].options?
Alternately, is there any way to achieve this using the select2 tagging feature? See https://select2.org/tagging. I could catch the CreateTag method and then create my new Client, returning the updated option information, although I create the Client asynchronously, so this doesn't match the pattern on the select2 documentation.
[oops this should have been tagged as a question]
Replies
I also see https://select2.org/programmatic-control/add-select-clear-items where it seems possible to add an option programmatically.
I was able to create my own AddOption method. Suggesting making something like this standard.
Thanks for posting this. The built in field types actually gained the ability to append options to an existing list recently, so Select2 probably should again that as well.
I've been considering making Select2 an integrated field type as it is popular and there are a lot of support questions about it, so integrating might help.
Allan