Tom-Select (or Selectize.js) Remote data for Option Groups

Viewed 58

I am trying to use remote data for tom-select (https://tom-select.js.org/examples/optgroups/). I am at a loss how to configure option groups with remote data. I have the select loading with remote data like this:

"optgroup": "1 Materials | 1.2 Gravel",
"value": 65,
"label": "1.2.1 Tanks"

From the docs I got the impression that you set optgroupField: 'optgroup' and the option groups would be set automatically. Do I need to add the optgroups array to my JSON data? I can't seem to find any examples of remote data with option groups anywhere.

tom-select shares much of it's code from Selectize.js so I am cross tagging this also.

1 Answers

I found a solution in the selectize world:

https://github.com/selectize/selectize.js/issues/151#issuecomment-111056161

I added a group id:

"optgroup_id": 13,
"optgroup": "1 Materials | 1.1 Pipe, valves & fittings",
"value": 5,
"label": "1.1.1 Line Pipe"

Reset the group field: optgroupField: 'optgroup_id' then added this after the json callback in load:

json.items.forEach((item) => {
this.addOptionGroup(item['optgroup_id'], { label: item['optgroup'] } );
  });
this.refreshItems()

I am also playing around with adding a second optgroups json array with just the groups to avoid cycling through all the options.

I hope there is a better answer - will leave this open for that. Hoping this helps someone else.

Related