From cdf57d7eea632b6eb5f7ef4c3c31d7eedeb32b6e Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Wed, 11 Aug 2021 19:48:19 +0200 Subject: [PATCH] web/elements: add support for dot-notation in input names Signed-off-by: Jens Langhammer --- web/src/elements/forms/Form.ts | 22 ++++++++++++++++++- web/src/elements/forms/ModalForm.ts | 34 +++++++++++++++-------------- 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/web/src/elements/forms/Form.ts b/web/src/elements/forms/Form.ts index 4962b1227..2ef6e09bc 100644 --- a/web/src/elements/forms/Form.ts +++ b/web/src/elements/forms/Form.ts @@ -140,13 +140,33 @@ export class Form extends LitElement { json[element.name] = element.checked; } else { for (let v = 0; v < values.length; v++) { - form._addSerializedElement(json, element.name, values[v]); + this.serializeFieldRecursive(element, values[v], json); } } }); return json as unknown as T; } + private serializeFieldRecursive( + element: HTMLInputElement, + value: unknown, + json: { [key: string]: unknown }, + ): void { + let parent = json; + if (!element.name.includes(".")) { + parent[element.name] = value; + return; + } + const nameElements = element.name.split("."); + for (let index = 0; index < nameElements.length - 1; index++) { + const nameEl = nameElements[index]; + // Ensure all nested structures exist + if (!(nameEl in parent)) parent[nameEl] = {}; + parent = parent[nameEl] as { [key: string]: unknown }; + } + parent[nameElements[nameElements.length - 1]] = value; + } + submit(ev: Event): Promise | undefined { ev.preventDefault(); const ironForm = this.shadowRoot?.querySelector("iron-form"); diff --git a/web/src/elements/forms/ModalForm.ts b/web/src/elements/forms/ModalForm.ts index 21088e06e..eb7891e3d 100644 --- a/web/src/elements/forms/ModalForm.ts +++ b/web/src/elements/forms/ModalForm.ts @@ -23,22 +23,24 @@ export class ModalForm extends ModalButton { if (!formPromise) { return Promise.reject(t`Form didn't return a promise for submitting`); } - return formPromise.then(() => { - if (this.closeAfterSuccessfulSubmit) { - this.open = false; - form?.resetForm(); - } - this.loading = false; - this.dispatchEvent( - new CustomEvent(EVENT_REFRESH, { - bubbles: true, - composed: true, - }), - ); - }).catch((exc) => { - this.loading = false; - throw exc; - }); + return formPromise + .then(() => { + if (this.closeAfterSuccessfulSubmit) { + this.open = false; + form?.resetForm(); + } + this.loading = false; + this.dispatchEvent( + new CustomEvent(EVENT_REFRESH, { + bubbles: true, + composed: true, + }), + ); + }) + .catch((exc) => { + this.loading = false; + throw exc; + }); } renderModalInner(): TemplateResult {