Dinamically set options on open

Hi,
I’m trying to create a custom data adapter to generate options dynamically, but I have 2 issues with my code (mostly grabbed from stackoverflow, but I don’t have the original anymore),
here’s a jsfiddle for it: https://jsfiddle.net/daf34thu/

First problem: when you click on the “Placeholder” nothing happens, but if you click on the rest of the space it works. It also works without a placeholder, but I would really like to keep it…
Second problem: every time the dropdown opens it forgets the previous value, so if you open the select box, select something, open it again and close it (maybe pressing esc), the value is gone…

Did anyone encounter any of these issues?
Thanks

To fix the first problem you need to make the placeholder element pass clicks through to the .select2-selection element. The easiest way to do that is to set pointer-events: none; in the placeholder element’s CSS:

<span class="select2-selection__placeholder" style="pointer-events: none;">Placeholder</span>

The second issue is that your custom DataAdapter just removes all of the current <option>s and then creates new <option>s based on the data array passed to the adapter. Since that data array doesn’t indicate which item(s) should be selected, no item is selected. Instead, you need to get the current selection(s), and then set the “selected” property of any data array elements matching the current selection(s) before calling this.addOptions(this.convertToOptions(data));. This code does the trick:

    CustomDataAdapter.prototype.updateOptions = function(data) {
      // Get the current selection(s):
      const selected = this.$element.select2("data");
      // Set the "selected" attribute of any matching items in the data array.
      for (const d of data) {
      	for (const s of selected) {
        	d.selected = (d.id === s.id);
        }
      }
      // Recreate the DOM <option>s.
      this.$element.find('option').remove();
      this.addOptions(this.convertToOptions(data));
    };

Here’s my fork of your fiddle proving it works: https://jsfiddle.net/jpisello/y6nwr0j3/12/

Thanks, that works as expected now.

In the meantime I was experimenting with this other jsfiddle:
https://jsfiddle.net/zku642n3/
in this case I don’t recreate the options every time, I just change the disabled attribute.
But as you can see, it doesn’t work when optgroups are used.
Could you help me with this too?
Thanks.