Skip to content

Commit 9de8feb

Browse files
committed
Update select component to allow finding options in arbitrary json
When json response contains other data than just array of option data, allow to access given array by specifying its path in "src" attribute.
1 parent f83fe4a commit 9de8feb

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

admin/app/javascript/solidus_admin/web_components/solidus_select.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,18 @@ class SolidusSelect extends HTMLSelectElement {
105105
this.tomselect.settings.load = null;
106106
}
107107

108+
// Fetch options from remote source. If options data is nested in json response, specify path to it within "data-src"
109+
// attribute after "::" separator.
110+
// E.g. https://whatcms.org/API/List data is deep nested in json response: `{ result: { list: [...] } }`, so
111+
// in order to access it, specify "data-src" as follows:
112+
// "data-src"="https://whatcms.org/API/List::result.list"
108113
async fetchOptions() {
109-
const response = await fetch(this.getAttribute("data-src"));
110-
return await response.json();
114+
const [url, dataPath] = this.getAttribute("data-src").split("::");
115+
const response = await fetch(url);
116+
const json = await response.json();
117+
if (!dataPath) return json;
118+
119+
return dataPath.split('.').reduce((acc, key) => acc && acc[key], json);
111120
}
112121
}
113122

admin/spec/components/previews/solidus_admin/ui/forms/select/component_preview.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,21 @@ def overview
88
render_with_template
99
end
1010

11+
# @param multiple toggle
12+
# @param latency toggle "Simulate request latency (2000ms)"
13+
def remote(multiple: false, latency: false)
14+
args = { label: "Label", name: "select", multiple: }
15+
delay_url = "app.requestly.io/delay/2000/" if latency
16+
src = "https://#{delay_url}whatcms.org/API/List::result.list"
17+
args.merge!(
18+
src:,
19+
"data-option-value-field": "id",
20+
"data-option-label-field": "label",
21+
)
22+
23+
render component("ui/forms/select").new(**args)
24+
end
25+
1126
# @param size select { choices: [s, m, l] }
1227
# @param options number
1328
# @param multiple toggle

0 commit comments

Comments
 (0)