From 107f0da88bea27bcb2c2aa84b1f7a66ee2660daf Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Tue, 30 Jan 2024 12:24:45 +0100 Subject: [PATCH] Allow config flow to show error per field (#19522) --- src/components/ha-alert.ts | 4 ++++ src/components/ha-form/ha-form.ts | 20 ++++++++++++++++++-- src/dialogs/config-flow/step-flow-form.ts | 15 +++++++++++++-- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/components/ha-alert.ts b/src/components/ha-alert.ts index 90c0decd98..790adb108c 100644 --- a/src/components/ha-alert.ts +++ b/src/components/ha-alert.ts @@ -154,6 +154,10 @@ class HaAlert extends LitElement { .issue-type.success::after { background-color: var(--success-color); } + :host ::slotted(ul) { + margin: 0; + padding-inline-start: 20px; + } `; } diff --git a/src/components/ha-form/ha-form.ts b/src/components/ha-form/ha-form.ts index 6cd8dfeb81..0d460098b0 100644 --- a/src/components/ha-form/ha-form.ts +++ b/src/components/ha-form/ha-form.ts @@ -45,7 +45,10 @@ export class HaForm extends LitElement implements HaFormElement { @property({ attribute: false }) public schema!: readonly HaFormSchema[]; - @property({ attribute: false }) public error?: Record; + @property({ attribute: false }) public error?: Record< + string, + string | string[] + >; @property({ attribute: false }) public warning?: Record; @@ -228,7 +231,20 @@ export class HaForm extends LitElement implements HaFormElement { return this.computeHelper ? this.computeHelper(schema) : ""; } - private _computeError(error, schema: HaFormSchema | readonly HaFormSchema[]) { + private _computeError( + error: string | string[], + schema: HaFormSchema | readonly HaFormSchema[] + ): string | TemplateResult { + if (Array.isArray(error)) { + return html`
    + ${error.map( + (err) => + html`
  • + ${this.computeError ? this.computeError(err, schema) : err} +
  • ` + )} +
`; + } return this.computeError ? this.computeError(error, schema) : error; } diff --git a/src/dialogs/config-flow/step-flow-form.ts b/src/dialogs/config-flow/step-flow-form.ts index fd7b28ea5e..bdea2195ed 100644 --- a/src/dialogs/config-flow/step-flow-form.ts +++ b/src/dialogs/config-flow/step-flow-form.ts @@ -201,8 +201,19 @@ class StepFlowForm extends LitElement { step, }); } catch (err: any) { - this._errorMsg = - (err && err.body && err.body.message) || "Unknown error occurred"; + if (err && err.body) { + if (err.body.message) { + this._errorMsg = err.body.message; + } + if (err.body.errors) { + this.step = { ...this.step, errors: err.body.errors }; + } + if (!err.body.message && !err.body.errors) { + this._errorMsg = "Unknown error occurred"; + } + } else { + this._errorMsg = "Unknown error occurred"; + } } finally { this._loading = false; }