From b56081405e8599749e5fbc8c7ea058880bcbc56e Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 22 Sep 2023 12:16:54 +0200 Subject: [PATCH] Handle initial values --- .../app/forms/RelationshipField.svelte | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/packages/client/src/components/app/forms/RelationshipField.svelte b/packages/client/src/components/app/forms/RelationshipField.svelte index 34c38de2e4..2c847a2b1e 100644 --- a/packages/client/src/components/app/forms/RelationshipField.svelte +++ b/packages/client/src/components/app/forms/RelationshipField.svelte @@ -37,17 +37,28 @@ }, }) - $: options = $fetch.rows $: tableDefinition = $fetch.definition $: selectedValue = multiselect ? flatten(fieldState?.value) ?? [] : flatten(fieldState?.value)?.[0] $: component = multiselect ? CoreMultiselect : CoreSelect $: expandedDefaultValue = expand(defaultValue) - $: primaryDisplay = tableDefinition?.primaryDisplay || "_id" + $: primaryDisplay = tableDefinition?.primaryDisplay + + $: initialValues = + initialValues || + (primaryDisplay && + fieldState?.value?.map(x => ({ + _id: x._id, + [primaryDisplay]: x.primaryDisplay, + }))) + + $: options = processOptions(selectedValue, $fetch.rows, initialValues) let lastFetchedTerm - $: { + $: search(fetchTerm) + + const search = fetchTerm => { const termChangedSinceFetch = (lastFetchedTerm || "") !== (fetchTerm || "") const allRowsFetched = !lastFetchedTerm && !$fetch.hasNextPage @@ -76,6 +87,22 @@ return values.map(value => (typeof value === "object" ? value._id : value)) } + const processOptions = (selectedValue, fetchedRows, initialValues = []) => { + selectedValue ??= [] + if (!Array.isArray(selectedValue)) { + selectedValue = [selectedValue] + } + + const missingItems = selectedValue + .filter(v => !fetchedRows.find(r => r._id === v)) + .map(v => initialValues.find(o => o._id === v)) + .filter(x => x) + + const result = [...missingItems, ...fetchedRows] + + return result + } + const getDisplayName = row => { return row?.[primaryDisplay] || "-" }