Select2: Refresh after selecting a new tag

I implemented a tag system in which you can select existing tags or add new tags. After selecting a new tag, he will continue to use the AJAX call.

To do this, I use the createTag and the select2:select event. Since I like to create a tag only when it is selected, I make an AJAX call for this if the select2:select event is select2:select .

The problem is that I need to update the already created select2 option with the identifier that I get from saving my new tag in the database. What is the cleanest solution for this?

Here is what I have:

 $('select.tags').select2({ tags: true, ajax: { url: '{{ path('tag_auto_complete') }}', processResults: function (data) { return { results: data.items, pagination: { more: false } }; } }, createTag: function (tag) { return { id: tag.term, // <-- this one should get exchanged after persisting the new tag text: tag.term, tag: true }; } }).on('select2:select', function (evt) { if(evt.params.data.tag == false) { return; } $.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) { // ----> Here I need to update the option created in "createTag" with the ID option_to_update.value = data.id; }, "json"); }); 
+5
source share
1 answer

My problem was that I did not add the new tag as the <option> in my own select box.

This is necessary because select2 checks the values ​​set in trough select2.val(values) if the <option> with this value exists. If select2 has not selected an extra value from the array and sets an array of values ​​that have the corresponding parameter tag in the base selection field.

So this is how it works now (for select2 4.0.x):

 $('select.tags').select2({ tags: true, ajax: { url: '{{ path('tag_auto_complete') }}', processResults: function (data) { return { results: data.items, pagination: { more: false } }; } }, createTag: function (tag) { return { id: tag.term, text: tag.term, tag: true }; } }).on('select2:select', function (evt) { if(evt.params.data.tag == false) { return; } var select2Element = $(this); $.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) { // Add HTML option to select field $('<option value="' + data.id + '">' + data.text + '</option>').appendTo(select2Element); // Replace the tag name in the current selection with the new persisted ID var selection = select2Element.val(); var index = selection.indexOf(data.text); if (index !== -1) { selection[index] = data.id.toString(); } select2Element.val(selection).trigger('change'); }, 'json'); }); 

The minimum AJAX response (JSON format) should look like this:

 [ {'id': '1', 'text': 'foo'}, {'id': '2', 'text': 'bar'}, {'id': '3', 'text': 'baz'} ] 

You can add additional data to each result to allow yourself to render a list of results with additional data in it.

+4
source

Source: https://habr.com/ru/post/1237693/


All Articles