Thomas
Thomas

Reputation: 956

Remove all previous selected options in Tom Select configured with external data

I have two Tom Select (select inputs) configured through Symfony UX Autocomplete and Stimulus :

Tom Select inputs

First holds the main category ("Batterie démarrage moto" in the example).

Second one is multiple and holds sub categories whose parent is the main category selected in first place ("Batterie moto AGM" and "Batterie moto GEL" in the example).

Each Tom Select is configured with AJAX external data.

When user update the main category, a change event is dispatched in main category :

_onConnect(event) {
    this.#tomSelect = event.detail.tomSelect;
    this.#tomSelect.on('change', this._onChange.bind(this));
}

_onChange(value) {
    this.dispatch("change", {
        detail: {
            id: value
        }
    });

    if (value) {
        this.#tomSelect.blur();
    }
}

Then a reset Stimulus action is executed in sub categories controller (data-action="erp--product--main-category:change@window->erp--product--sub-categories#reset") to :

Sub categories Tom Select displays refreshed results but previous selected sub categories still appears in dropdown among new records :

Previous selected options still appear

These options remains in select element :

enter image description here

I tried multiple solutions through our beloved Stack Overflow and the web :

# this.#tomSelect is the Tom Select instance
this.#tomSelect.clear();
this.#tomSelect.clearOptions();
this.#tomSelect.clearCache();
this.#tomSelect.refreshOptions();
this.#tomSelect.sync();

I tried to force these Tom Select options through Symfony :

"tom_select_options" => [
    "create" => false,
    "persist" => false,
]

The only way I found is to reset select HTML content after clearing Tom Select options :

this.#tomSelect.clear();
this.#tomSelect.clearOptions();

this.element.innerHTML = '';

Do you think this is the best solution ?

What can I do otherwise ?

Upvotes: 2

Views: 684

Answers (1)

Chopchop
Chopchop

Reputation: 2949

I don't have simulus UX but I had the same issue with tom-select. I had to clear Options manually after each ajax call. I still post the code for those who land here like me.

new TomSelect('#select-repo',{
        valueField: 'url',
        labelField: 'name',
        searchField: 'name',
        // fetch remote data
        load: function(query, callback) {
            var self = this;
            var url = 'https://api.github.com/search/repositories?q=toto'
            fetch(url)
                .then(response => response.json())
                .then(json => {
                    self.clearOptions();//needed to reset options
                    callback(json.items);
                }).catch(()=>{
                    callback();
                });

        },

Upvotes: 0

Related Questions