From 4e9fe01ef678a093706104fb60dad7fe0d9947a9 Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Fri, 29 Jan 2021 16:40:19 +0000 Subject: [PATCH] Automatically make forms use latest data context if it matches --- packages/standard-components/manifest.json | 4 --- .../standard-components/src/forms/Form.svelte | 25 ++++++++++++++++--- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/standard-components/manifest.json b/packages/standard-components/manifest.json index a0d39b82d4..107eead5f7 100644 --- a/packages/standard-components/manifest.json +++ b/packages/standard-components/manifest.json @@ -1132,7 +1132,6 @@ "name": "Text Field", "icon": "ri-edit-box-line", "styleable": true, - "bindable": true, "settings": [ { "type": "field/string", @@ -1155,7 +1154,6 @@ "name": "Number Field", "icon": "ri-edit-box-line", "styleable": true, - "bindable": true, "settings": [ { "type": "field/number", @@ -1178,7 +1176,6 @@ "name": "Options Picker", "icon": "ri-edit-box-line", "styleable": true, - "bindable": true, "settings": [ { "type": "field/options", @@ -1202,7 +1199,6 @@ "name": "Checkbox", "icon": "ri-edit-box-line", "styleable": true, - "bindable": true, "settings": [ { "type": "field/boolean", diff --git a/packages/standard-components/src/forms/Form.svelte b/packages/standard-components/src/forms/Form.svelte index 5edeb10447..bcbe084986 100644 --- a/packages/standard-components/src/forms/Form.svelte +++ b/packages/standard-components/src/forms/Form.svelte @@ -10,16 +10,27 @@ const { styleable, API, setBindableValue, DataProvider } = getContext("sdk") const component = getContext("component") + const dataContext = getContext("data") let loaded = false let schema let table let fieldMap = {} + // Checks if the closest data context matches the model for this forms + // datasource, and use it as the initial form values if so + const getInitialValues = context => { + return context && context.tableId === datasource?.tableId ? context : {} + } + + // Use the closest data context as the initial form values if it matches + const initialValues = getInitialValues( + $dataContext[$dataContext.closestComponentId] + ) + // Form state contains observable data about the form - const formState = writable({ values: {}, errors: {}, valid: true }) + const formState = writable({ values: initialValues, errors: {}, valid: true }) $: updateFormState(fieldMap) - $: setBindableValue($component.id, $formState.values) // Form API contains functions to control the form const formApi = { @@ -71,7 +82,7 @@ fieldId: `${Math.random() .toString(32) .substr(2)}/${field}`, - value: null, + value: initialValues[field] ?? null, error: null, valid: true, }) @@ -79,7 +90,7 @@ // Updates the form states from the field data const updateFormState = fieldMap => { - let values = {} + let values = { ...initialValues } let errors = {} Object.entries(fieldMap).forEach(([field, formField]) => { const fieldState = get(formField.fieldState) @@ -126,3 +137,9 @@ {/if} + +