-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbeacon_form_controller.js
More file actions
51 lines (40 loc) · 1.55 KB
/
beacon_form_controller.js
File metadata and controls
51 lines (40 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Controller } from "@hotwired/stimulus"
import { get } from "@rails/request.js"
export default class extends Controller {
static targets = ["languageSelect", "regionSelect", "topicsSelect", "providersSelect"]
static values = { filterUrl: String }
connect() {
// Defer until select-tags children have initialized their TomSelect instances
requestAnimationFrame(() => this.fetchOptions())
}
fetchOptions() {
const params = new URLSearchParams()
const languageId = this.languageSelectTarget.value
const regionId = this.regionSelectTarget.value
if (languageId) params.set("language_id", languageId)
if (regionId) params.set("region_id", regionId)
get(`${this.filterUrlValue}?${params}`, { responseKind: "json" })
.then(response => response.json)
.then(data => {
this.#updateSelect(this.topicsSelectTarget, data.topics, "title")
this.#updateSelect(this.providersSelectTarget, data.providers, "name")
})
}
#updateSelect(selectElement, items, textKey) {
const tomSelect = selectElement.tomselect
if (!tomSelect) return
const previousValues = [].concat(tomSelect.getValue())
tomSelect.clear(true)
tomSelect.clearOptions()
items.forEach(item => {
tomSelect.addOption({ value: String(item.id), text: item[textKey] })
})
const stillValidValues = previousValues.filter(v =>
items.some(item => String(item.id) === v)
)
if (stillValidValues.length > 0) {
tomSelect.setValue(stillValidValues, true)
}
tomSelect.refreshOptions(false)
}
}