diff --git a/src/Autocomplete/assets/src/controller.ts b/src/Autocomplete/assets/src/controller.ts index 62fe734ecb..b9370c9919 100644 --- a/src/Autocomplete/assets/src/controller.ts +++ b/src/Autocomplete/assets/src/controller.ts @@ -177,18 +177,21 @@ export default class extends Controller { } #createAutocompleteWithHtmlContents(): TomSelect { - const config = this.#mergeObjects(this.#getCommonConfig(), { + const commonConfig = this.#getCommonConfig(); + const labelField = commonConfig.labelField ?? 'text'; + + const config = this.#mergeObjects(commonConfig, { maxOptions: this.getMaxOptions(), score: (search: string) => { const scoringFunction = this.tomSelect.getScoreFunction(search); return (item: any) => { // strip HTML tags from each option's searchable text - return scoringFunction({ ...item, text: this.#stripTags(item.text) }); + return scoringFunction({ ...item, text: this.#stripTags(item[labelField]) }); }; }, render: { - item: (item: any) => `
${item.text}
`, - option: (item: any) => `
${item.text}
`, + item: (item: any) => `
${item[labelField]}
`, + option: (item: any) => `
${item[labelField]}
`, }, }); @@ -196,7 +199,10 @@ export default class extends Controller { } #createAutocompleteWithRemoteData(autocompleteEndpointUrl: string, minCharacterLength: number | null): TomSelect { - const config: RecursivePartial = this.#mergeObjects(this.#getCommonConfig(), { + const commonConfig = this.#getCommonConfig(); + const labelField = commonConfig.labelField ?? 'text'; + + const config: RecursivePartial = this.#mergeObjects(commonConfig, { firstUrl: (query: string) => { const separator = autocompleteEndpointUrl.includes('?') ? '&' : '?'; @@ -241,8 +247,8 @@ export default class extends Controller { // avoid extra filtering after results are returned score: (search: string) => (item: any) => 1, render: { - option: (item: any) => `
${item.text}
`, - item: (item: any) => `
${item.text}
`, + option: (item: any) => `
${item[labelField]}
`, + item: (item: any) => `
${item[labelField]}
`, loading_more: (): string => { return `
${this.loadingMoreTextValue}
`; },