0

I have a form to create new Objects, which gives the possibility to add multiple Keywords via a Select2.

I use Symfony ; the Keywords are taken from an entity. Adding existing keyword in the Select2 list work perfectly fine.

Now I want to give the user the possibility to add brand new keywords, and that those new keywords directly appears in the Select2 list.

So I created a "Add Keyword" button on my "new object form", which leads to a "New Keyword" form (a Bootstrap modal window).

The Javascript used to add the newly created keyword to the Select2 list is the following:

function OnSuccess(result){
    var keywordsSelected = new Array($("#object_keywords").select2("val")); 
    $('#object_keywords').append('<option value="'+result.id+'" selected="selected">'+result.name+'</option>');
    keywordsSelected.push(result.id);
    $("#object_keywords").select2("val", keywordsSelected); // 
    $('#addKeyword').modal('hide');
}

Now the weird thing:

  • I click on my "Add keyword" button, I fill the name of the new keyword in the "new Keyword" form, I validate, the new keyword is added in the Select2 list --> everything is fine
  • I do the same thing another time --> everything is fine, the second new keyword is added to the Select2 list near the previous one
  • I do the same thing a third time and... the third keyword is added but the two first disappear!!

This appends even if the 2 fisrt are "old" keywords already existing in the DB, but this doesn't append if I add only "old" keywords (I can add as many as I want).

Do you have any idea where the problem could come from?

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
Blacksad
  • 1,230
  • 1
  • 14
  • 23

1 Answers1

0

Well...

I continued to search and by chance I found something which seems to work (i.e. I didn't find a case where it doesn't, yet).

I changed the order of the lines and added a "clear Select2" instruction:

function OnSuccess(result){
    $('#addKeyword').modal('hide');  
    $('#webobs_eventbundle_event_keywords').append('<option value="'+result.id+'" selected="selected">'+result.name+'</option>'); // Add the new Keyword in the list
    var keywordsSelected = $("#webobs_eventbundle_event_keywords").select2("val");
    keywordsSelected.push(result.id);
    $("#webobs_eventbundle_event_keywords").select2("val", null);
    $("#webobs_eventbundle_event_keywords").select2("val", keywordsSelected);     
}

Anyway, I'm still interested in you opinion about this problem, because I don't really see the reason why this code works and not the first one...

Blacksad
  • 1,230
  • 1
  • 14
  • 23