Dan Tappin
Dan Tappin

Reputation: 3032

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

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.

Upvotes: 2

Views: 1247

Answers (2)

Rhodri Pugh
Rhodri Pugh

Reputation: 1

With TomSelect you can format remote data into option groups like this:

new TomSelect('#id', {
  // these are the defaults
  optgroupField: 'optgroup',
  optgroupValueField: 'value',
  optgroupLabelField: 'label',
  // specify your option groups
  optgroups: [
    {value: 'foo', label: 'Foo Group'},
    {value: 'bar', label: 'Bar Group'},
  ],
});

Your data should then include an optgroup property for each item.

[
  {
    id: 1,
    name: "Result",
    optgroup: "foo",
  }
]

Upvotes: 0

Dan Tappin
Dan Tappin

Reputation: 3032

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.

Upvotes: 0

Related Questions