Skip to content

Commit 8782509

Browse files
committed
[Autocomplete] Allow configuring TomSelect’s labelField
1 parent 89c7fa9 commit 8782509

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/Autocomplete/assets/src/controller.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -177,26 +177,32 @@ export default class extends Controller {
177177
}
178178

179179
#createAutocompleteWithHtmlContents(): TomSelect {
180-
const config = this.#mergeObjects(this.#getCommonConfig(), {
180+
const commonConfig = this.#getCommonConfig();
181+
const labelField = commonConfig.labelField ?? 'text';
182+
183+
const config = this.#mergeObjects(commonConfig, {
181184
maxOptions: this.getMaxOptions(),
182185
score: (search: string) => {
183186
const scoringFunction = this.tomSelect.getScoreFunction(search);
184187
return (item: any) => {
185188
// strip HTML tags from each option's searchable text
186-
return scoringFunction({ ...item, text: this.#stripTags(item.text) });
189+
return scoringFunction({ ...item, text: this.#stripTags(item[labelField]) });
187190
};
188191
},
189192
render: {
190-
item: (item: any) => `<div>${item.text}</div>`,
191-
option: (item: any) => `<div>${item.text}</div>`,
193+
item: (item: any) => `<div>${item[labelField]}</div>`,
194+
option: (item: any) => `<div>${item[labelField]}</div>`,
192195
},
193196
});
194197

195198
return this.#createTomSelect(config);
196199
}
197200

198201
#createAutocompleteWithRemoteData(autocompleteEndpointUrl: string, minCharacterLength: number | null): TomSelect {
199-
const config: RecursivePartial<TomSettings> = this.#mergeObjects(this.#getCommonConfig(), {
202+
const commonConfig = this.#getCommonConfig();
203+
const labelField = commonConfig.labelField ?? 'text';
204+
205+
const config: RecursivePartial<TomSettings> = this.#mergeObjects(commonConfig, {
200206
firstUrl: (query: string) => {
201207
const separator = autocompleteEndpointUrl.includes('?') ? '&' : '?';
202208

@@ -241,8 +247,8 @@ export default class extends Controller {
241247
// avoid extra filtering after results are returned
242248
score: (search: string) => (item: any) => 1,
243249
render: {
244-
option: (item: any) => `<div>${item.text}</div>`,
245-
item: (item: any) => `<div>${item.text}</div>`,
250+
option: (item: any) => `<div>${item[labelField]}</div>`,
251+
item: (item: any) => `<div>${item[labelField]}</div>`,
246252
loading_more: (): string => {
247253
return `<div class="loading-more-results">${this.loadingMoreTextValue}</div>`;
248254
},

0 commit comments

Comments
 (0)