menu

Questions & Answers

tom-select how to keep order when using drag and drop plugin

I'm using tom-select for multiple select field with drag & drop plugin

Options provided to the select are alphabetically sorted, everything works fine when I choose some items, they are saved in db in the order I'v sorted them manually, as expected. Problem is that when I reload the page those selected items are shown in alphabetical order anyway. Is there any way to sort them custom way ?

Answers(2) :

I'v resolved it by passing selected ids if I want to have it ordered by selection order, not options order, part of stimulus controller:

static values = { selectedIds: Array }

...

connect(){
      if(this.selectedIdsValue && this.selectedIdsValue.length > 0) {
        config.items = this.selectedIdsValue
      }
}

Tom Select will order items (selected options) as instructed by your code.

new TomSelect('#your-select',{
  items:['a','b']
});

vs

new TomSelect('#your-select',{
  items:['b','a']
});

If you don't tell Tom Select how you want items ordered, it will use the order of the options in the select.