Add hydrateForm.

This commit is contained in:
Austin Smith
2025-10-07 09:17:00 -04:00
parent ceeb4c4b0f
commit ed00ede04f

View File

@@ -121,6 +121,10 @@ export class Declaform extends HTMLElement {
for (const [name, inputs] of inputGroups.entries()) { for (const [name, inputs] of inputGroups.entries()) {
this._fields.push(new Field(name, inputs)) this._fields.push(new Field(name, inputs))
} }
const src = this.getAttribute('src');
if (src) {
this.hydrateForm(src);
}
} }
get form() { get form() {
@@ -151,6 +155,24 @@ export class Declaform extends HTMLElement {
} }
return obj; return obj;
} }
private async hydrateForm(endpoint: string) {
const response = await fetch(endpoint);
const obj = await response.json();
const populateFields = (current: Record<string, any>, path: string) => {
for (const key of Object.keys(current)) {
const value = current[key];
const propPath = (path.length) ? `${path}.${key}` : key;
if (typeof value !== 'object') {
const fields = this.fields.filter(x => x.name === propPath);
fields.forEach(x => x.value = value);
} else {
populateFields(current[key], propPath);
}
}
};
populateFields(obj, '');
}
} }
customElements.define('decla-form', Declaform); customElements.define('decla-form', Declaform);