web/elements: add support for dot-notation in input names

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-08-11 19:48:19 +02:00
parent b237f2ddfb
commit cdf57d7eea
2 changed files with 39 additions and 17 deletions

View file

@ -140,13 +140,33 @@ export class Form<T> extends LitElement {
json[element.name] = element.checked; json[element.name] = element.checked;
} else { } else {
for (let v = 0; v < values.length; v++) { 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; 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<unknown> | undefined { submit(ev: Event): Promise<unknown> | undefined {
ev.preventDefault(); ev.preventDefault();
const ironForm = this.shadowRoot?.querySelector("iron-form"); const ironForm = this.shadowRoot?.querySelector("iron-form");

View file

@ -23,22 +23,24 @@ export class ModalForm extends ModalButton {
if (!formPromise) { if (!formPromise) {
return Promise.reject(t`Form didn't return a promise for submitting`); return Promise.reject(t`Form didn't return a promise for submitting`);
} }
return formPromise.then(() => { return formPromise
if (this.closeAfterSuccessfulSubmit) { .then(() => {
this.open = false; if (this.closeAfterSuccessfulSubmit) {
form?.resetForm(); this.open = false;
} form?.resetForm();
this.loading = false; }
this.dispatchEvent( this.loading = false;
new CustomEvent(EVENT_REFRESH, { this.dispatchEvent(
bubbles: true, new CustomEvent(EVENT_REFRESH, {
composed: true, bubbles: true,
}), composed: true,
); }),
}).catch((exc) => { );
this.loading = false; })
throw exc; .catch((exc) => {
}); this.loading = false;
throw exc;
});
} }
renderModalInner(): TemplateResult { renderModalInner(): TemplateResult {