Beautiful Open-Source Form Builder
Improve form save validation errors (#1211)
Julien Nahumaab51bfafc73
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vueindex cbef4e917..af39cf9ee 100644--- a/client/components/open/forms/components/FormEditor.vue+++ b/client/components/open/forms/components/FormEditor.vue@@ -37,6 +37,7 @@</div><FormEditorNavbar+ ref="formEditorNavbar":back-button="backButton":update-form-loading="form.busy":save-button-class="saveButtonClass"@@ -91,8 +92,10 @@<!-- Form Error Modal --><FormErrorModal:show="showFormErrorModal"- :validation-error-response="validationErrorResponse"- @close="showFormErrorModal = false"+ :error-summary="saveErrorSummary"+ @close="handleFormErrorModalClose"+ @edit-field="editInvalidField"+ @edit-computed-variable="editInvalidComputedVariable"/><!-- Logic Confirmation Modal -->@@ -129,6 +132,7 @@ import LogicConfirmationModal from '~/components/forms/heavy/LogicConfirmationMoimport { formsApi } from "~/api"import { useResizable } from '~/composables/components/useResizable'import ResizeHandle from '~/components/global/ResizeHandle.vue'+import { normalizeFormSaveErrors } from '~/lib/forms/form-save-errors'// Define propsconst props = defineProps({@@ -168,6 +172,7 @@ const showLogicConfirmationModal = ref(false)const validationErrorResponse = ref(null)const createdFormSlug = ref(null)const logicErrors = ref([])+const formEditorNavbar = ref(null)const route = useRoute()const { emitFormSaved, emitNavigateBack } = useEditorEmbedBridge()@@ -196,6 +201,14 @@ watch(isVisible, (newValue) => {// Composablesconst { content: form } = storeToRefs(useWorkingFormStore())+const saveErrorSummary = computed(() => {+ return normalizeFormSaveErrors(+ validationErrorResponse.value,+ form.value?.properties || [],+ form.value?.computed_variables || [],+ )+})+watch(() => form.value,(f) => {@@ -267,6 +280,61 @@ const showValidationErrors = () => {showFormErrorModal.value = true}+const handleFormErrorModalClose = () => {+ showFormErrorModal.value = false++ nextTick(() => {+ document.querySelector('[data-testid="save-form-button"]')?.focus()+ })+}++const editInvalidField = ({ fieldId, fieldIndex, targetTab }) => {+ const properties = form.value?.properties || []+ const indexedField = Number.isInteger(fieldIndex) ? properties[fieldIndex] : null+ const indexedFieldMatches = indexedField && (!fieldId || indexedField.id === fieldId)+ const currentFieldIndex = indexedFieldMatches+ ? fieldIndex+ : properties.findIndex(property => property?.id === fieldId)+ const targetIndex = currentFieldIndex >= 0 ? currentFieldIndex : fieldIndex++ if (!Number.isInteger(targetIndex) || !properties[targetIndex]) {+ handleFormErrorModalClose()+ return+ }++ showFormErrorModal.value = false+ workingFormStore.activeTab = 'build'+ workingFormStore.openSettingsForField(targetIndex, true, targetTab)++ nextTick(() => {+ document.getElementById('form-field-settings')?.focus()+ document.getElementById(`block-${properties[targetIndex].id}`)?.scrollIntoView({+ block: 'center',+ behavior: 'auto',+ })+ })+}++const editInvalidComputedVariable = ({ variableId, variableIndex }) => {+ const computedVariables = form.value?.computed_variables || []+ const indexedVariable = computedVariables[variableIndex]+ const targetVariable = indexedVariable || computedVariables.find(variable => variable?.id === variableId)++ if (!targetVariable) {+ handleFormErrorModalClose()+ return+ }++ showFormErrorModal.value = false++ nextTick(() => {+ formEditorNavbar.value?.openComputedVariable({+ variableId: targetVariable.id,+ variableIndex: computedVariables.indexOf(targetVariable),+ })+ })+}+const saveForm = () => {// Apply defaults to the formconst defaultedData = setFormDefaults(form.value.data())diff --git a/client/components/open/forms/components/FormEditorNavbar.vue b/client/components/open/forms/components/FormEditorNavbar.vueindex d8d47c510..36616590f 100644--- a/client/components/open/forms/components/FormEditorNavbar.vue+++ b/client/components/open/forms/components/FormEditorNavbar.vue@@ -32,6 +32,8 @@/><FormSettingsModalv-model="settingsModal"+ v-model:active-tab="settingsModalActiveTab"+ :computed-variable-edit-request="computedVariableEditRequest"@close="settingsModal = false"hydrate-on-interaction/>@@ -157,6 +159,22 @@ const form = computed(() => workingFormStore.content)const { activeTab } = storeToRefs(workingFormStore)const settingsModal = ref(false)+const settingsModalActiveTab = ref('general')+const computedVariableEditRequest = ref(null)+let computedVariableEditRequestId = 0++function openComputedVariable({ variableId, variableIndex }) {+ computedVariableEditRequestId += 1+ computedVariableEditRequest.value = {+ variableId,+ variableIndex,+ requestId: computedVariableEditRequestId,+ }+ settingsModalActiveTab.value = 'variables'+ settingsModal.value = true+}++defineExpose({ openComputedVariable })const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))</script>diff --git a/client/components/open/forms/components/computed-variables/ComputedVariableModal.vue b/client/components/open/forms/components/computed-variables/ComputedVariableModal.vueindex ca5df87ba..416978218 100644--- a/client/components/open/forms/components/computed-variables/ComputedVariableModal.vue+++ b/client/components/open/forms/components/computed-variables/ComputedVariableModal.vue@@ -4,7 +4,10 @@:ui="{ content: 'sm:max-w-5xl' }"><template #content>- <div class="flex flex-col h-[80vh] bg-white">+ <div+ data-testid="computed-variable-modal"+ class="flex flex-col h-[80vh] bg-white"+ ><!-- Header --><div class="flex items-center justify-between p-4 border-b flex-shrink-0"><h3 class="text-lg font-semibold">diff --git a/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue b/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vueindex f4bae15d1..09186853a 100644--- a/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue+++ b/client/components/open/forms/components/computed-variables/ComputedVariablesTab.vue@@ -1,5 +1,8 @@<template>- <div class="p-4">+ <div+ data-testid="computed-variables-tab"+ class="p-4"+ ><div class="flex justify-between items-start gap-4 mb-4"><div class="min-w-0"><h3 class="text-lg font-semibold text-gray-900">@@ -98,6 +101,13 @@ import ComputedVariableCard from './ComputedVariableCard.vue'import ComputedVariableModal from './ComputedVariableModal.vue'import { generateUUID } from '~/lib/utils.js'+const props = defineProps({+ editRequest: {+ type: Object,+ default: null,+ },+})+const workingFormStore = useWorkingFormStore()const form = computed(() => workingFormStore.content)@@ -123,6 +133,22 @@ function openEditModal(variable) {showModal.value = true}+watch(() => props.editRequest, (request) => {+ if (!request) {+ return+ }++ const indexedVariable = Number.isInteger(request.variableIndex)+ ? computedVariables.value[request.variableIndex]+ : null+ const variable = indexedVariable+ || computedVariables.value.find(item => item?.id === request.variableId)++ if (variable) {+ openEditModal(variable)+ }+}, { immediate: true })+function saveVariable(variable) {const variables = [...computedVariables.value]diff --git a/client/components/open/forms/components/form-components/FormErrorModal.vue b/client/components/open/forms/components/form-components/FormErrorModal.vueindex fc77c2cd8..2b2cea7f3 100644--- a/client/components/open/forms/components/form-components/FormErrorModal.vue+++ b/client/components/open/forms/components/form-components/FormErrorModal.vue@@ -1,35 +1,169 @@<template><UModalv-model:open="isOpen"- :ui="{ content: 'sm:max-w-lg' }"- title="We couldn't save your form"+ :ui="{ content: 'sm:max-w-xl' }"+ :title="modalTitle"><template #body><div- v-if="validationErrorResponse"- class="p-4 border border-red-200 rounded-lg bg-red-50"+ data-testid="form-save-error-modal"+ class="space-y-4"+ role="alert"+ aria-live="assertive"><p- v-if="validationErrorResponse.message"- class="text-red-800 mb-3"- v-text="validationErrorResponse.message"- />- <ul- v-if="validationErrors.length > 0"- class="list-disc list-inside text-red-700 space-y-1"+ v-if="hasStructuredErrors"+ class="text-sm text-neutral-600">- <li- v-for="(err, key) in validationErrors"- :key="key"+ Review the items below, then try saving your form again.+ </p>++ <div+ v-for="group in fieldGroups"+ :key="group.key"+ :data-testid="`form-save-error-field-${group.fieldId || group.fieldIndex}`"+ class="rounded-lg border border-neutral-200 bg-white p-4"+ >+ <div class="flex items-start gap-3">+ <div class="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full bg-red-50 text-red-600">+ <Icon+ name="i-heroicons-exclamation-circle"+ class="size-5"+ />+ </div>++ <div class="min-w-0 flex-1">+ <div class="flex flex-wrap items-start justify-between gap-3">+ <div class="min-w-0">+ <p class="truncate font-medium text-neutral-900">+ {{ group.fieldName }}+ </p>+ <p+ v-if="fieldTypeLabel(group.fieldType)"+ class="mt-0.5 text-xs text-neutral-500"+ >+ {{ fieldTypeLabel(group.fieldType) }}+ </p>+ </div>++ <UButton+ v-if="group.canNavigate"+ color="primary"+ variant="soft"+ size="sm"+ icon="i-heroicons-pencil-square"+ :aria-label="`Edit ${group.fieldName}`"+ :data-testid="`edit-form-field-${group.fieldId || group.fieldIndex}`"+ @click="editField(group)"+ >+ Edit field+ </UButton>+ </div>++ <ul class="mt-3 space-y-1 text-sm text-red-700">+ <li+ v-for="message in group.messages"+ :key="message"+ class="flex gap-2"+ >+ <span aria-hidden="true">•</span>+ <span>{{ message }}</span>+ </li>+ </ul>+ </div>+ </div>+ </div>++ <div+ v-for="group in computedVariableGroups"+ :key="group.key"+ :data-testid="`form-save-error-variable-${group.variableId || group.variableIndex}`"+ class="rounded-lg border border-neutral-200 bg-white p-4"+ >+ <div class="flex items-start gap-3">+ <div class="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full bg-red-50 text-red-600">+ <Icon+ name="i-heroicons-variable"+ class="size-5"+ />+ </div>++ <div class="min-w-0 flex-1">+ <div class="flex flex-wrap items-start justify-between gap-3">+ <div class="min-w-0">+ <p class="truncate font-medium text-neutral-900">+ {{ group.variableName }}+ </p>+ <p class="mt-0.5 text-xs text-neutral-500">+ Computed variable+ </p>+ </div>++ <UButton+ v-if="group.canNavigate"+ color="primary"+ variant="soft"+ size="sm"+ icon="i-heroicons-pencil-square"+ :aria-label="`Edit ${group.variableName}`"+ :data-testid="`edit-computed-variable-${group.variableId || group.variableIndex}`"+ @click="editComputedVariable(group)"+ >+ Edit variable+ </UButton>+ </div>++ <ul class="mt-3 space-y-1 text-sm text-red-700">+ <li+ v-for="message in group.messages"+ :key="message"+ class="flex gap-2"+ >+ <span aria-hidden="true">•</span>+ <span>{{ message }}</span>+ </li>+ </ul>+ </div>+ </div>+ </div>++ <div+ v-if="generalErrors.length > 0"+ data-testid="form-save-general-errors"+ class="rounded-lg border border-red-200 bg-red-50 p-4"+ >+ <div+ v-for="error in generalErrors"+ :key="error.key"+ class="not-last:mb-4">- {{ err }}- </li>- </ul>+ <p class="font-medium text-red-900">+ {{ error.label }}+ </p>+ <ul class="mt-2 space-y-1 text-sm text-red-700">+ <li+ v-for="message in error.messages"+ :key="message"+ class="flex gap-2"+ >+ <span aria-hidden="true">•</span>+ <span>{{ message }}</span>+ </li>+ </ul>+ </div>+ </div>++ <div+ v-if="!hasStructuredErrors && fallbackMessage"+ class="rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-800"+ >+ {{ fallbackMessage }}+ </div></div></template><template #footer>- <div class="flex justify-end">+ <div class="flex w-full justify-end"><UButtoncolor="neutral"variant="outline"@@ -43,37 +177,78 @@</template><script setup>+import blocksTypes from '~/data/blocks_types.json'+const props = defineProps({show: { type: Boolean, required: true },- validationErrorResponse: { type: Object, required: false },+ errorSummary: {+ type: Object,+ default: () => ({+ fieldGroups: [],+ computedVariableGroups: [],+ generalErrors: [],+ issueCount: 0,+ fieldCount: 0,+ computedVariableCount: 0,+ fallbackMessage: null,+ }),+ },+})++const emit = defineEmits(['close', 'edit-field', 'edit-computed-variable'])++const fieldGroups = computed(() => props.errorSummary?.fieldGroups || [])+const computedVariableGroups = computed(() => props.errorSummary?.computedVariableGroups || [])+const generalErrors = computed(() => props.errorSummary?.generalErrors || [])+const fallbackMessage = computed(() => props.errorSummary?.fallbackMessage || null)+const hasStructuredErrors = computed(() => {+ return fieldGroups.value.length > 0+ || computedVariableGroups.value.length > 0+ || generalErrors.value.length > 0})-const emit = defineEmits(['close'])+const modalTitle = computed(() => {+ const fieldCount = fieldGroups.value.length+ const variableCount = computedVariableGroups.value.length+ const issueCount = fieldCount + variableCount + generalErrors.value.length-const validationErrors = computed(() => {- if (!props.validationErrorResponse?.errors) {- return []+ if (issueCount === 0) {+ return "We couldn't save your form"}- const errors = Object.values(props.validationErrorResponse.errors).map((err) => {- return Array.isArray(err) ? err[0] : err- })+ if (variableCount === 0 && generalErrors.value.length === 0) {+ return `Fix ${fieldCount} ${fieldCount === 1 ? 'field' : 'fields'} before saving`+ }++ if (fieldCount === 0 && generalErrors.value.length === 0) {+ return `Fix ${variableCount} ${variableCount === 1 ? 'variable' : 'variables'} before saving`+ }- return errors.filter((err) => err !== props.validationErrorResponse.message)+ return `Fix ${issueCount} ${issueCount === 1 ? 'issue' : 'issues'} before saving`})-// Modal stateconst isOpen = computed({get: () => props.show,set: (value) => {if (!value) {emit('close')}- }+ },})-// Methods-const closeModal = () => {+function fieldTypeLabel(fieldType) {+ return blocksTypes[fieldType]?.title || fieldType || null+}++function editField(group) {+ emit('edit-field', group)+}++function editComputedVariable(group) {+ emit('edit-computed-variable', group)+}++function closeModal() {isOpen.value = false}</script>diff --git a/client/components/open/forms/components/form-components/FormSettingsModal.vue b/client/components/open/forms/components/form-components/FormSettingsModal.vueindex 2e42b5af3..2f987c643 100644--- a/client/components/open/forms/components/form-components/FormSettingsModal.vue+++ b/client/components/open/forms/components/form-components/FormSettingsModal.vue@@ -57,7 +57,7 @@label="Variables"icon="i-heroicons-variable">- <ComputedVariablesTab />+ <ComputedVariablesTab :edit-request="computedVariableEditRequest" /></SettingsModalPage></SettingsModal>@@ -84,6 +84,10 @@ const props = defineProps({activeTab: {type: String,default: 'general'+ },+ computedVariableEditRequest: {+ type: Object,+ default: null}})@@ -112,4 +116,4 @@ defineShortcuts({}}})-</script>\ No newline at end of file+</script>diff --git a/client/components/open/forms/fields/FormFieldEdit.vue b/client/components/open/forms/fields/FormFieldEdit.vueindex d782f4fbc..6f0a9d9c0 100644--- a/client/components/open/forms/fields/FormFieldEdit.vue+++ b/client/components/open/forms/fields/FormFieldEdit.vue@@ -1,5 +1,9 @@<template><div+ id="form-field-settings"+ data-testid="form-field-settings"+ tabindex="-1"+ aria-label="Field settings":class="{ 'sidebar-bounce': sidebarBounce }"class="sidebar-container">@@ -252,7 +256,10 @@ const dropdownItems = computed(() => {})defineShortcuts(extractShortcuts(dropdownItems.value))-const activeTab = ref('options')+const activeTab = computed({+ get: () => workingFormStore.selectedFieldTab,+ set: value => workingFormStore.selectedFieldTab = value,+})const tabItems = computed(() => {const commonTabs = [diff --git a/client/lib/forms/form-save-errors.js b/client/lib/forms/form-save-errors.jsnew file mode 100644index 000000000..f39f5d828--- /dev/null+++ b/client/lib/forms/form-save-errors.js@@ -0,0 +1,137 @@+const AGGREGATE_MESSAGES = new Set([+ 'One or more properties have validation errors.',+ 'One or more computed variables have validation errors.',+])++const GENERAL_ERROR_LABELS = {+ properties: 'Form fields',+ computed_variables: 'Computed variables',+}++function normalizeMessages(messages) {+ const values = Array.isArray(messages) ? messages : [messages]++ return values+ .filter(message => message !== null && message !== undefined)+ .map(message => String(message).trim())+ .filter(message => message.length > 0 && !AGGREGATE_MESSAGES.has(message))+}++function addUniqueMessages(target, messages) {+ messages.forEach((message) => {+ if (!target.includes(message)) {+ target.push(message)+ }+ })+}++function humanizeErrorKey(key) {+ if (GENERAL_ERROR_LABELS[key]) {+ return GENERAL_ERROR_LABELS[key]+ }++ const rootKey = key.split('.')[0]+ const label = GENERAL_ERROR_LABELS[rootKey] || rootKey++ return label+ .replaceAll('_', ' ')+ .replace(/^\w/, character => character.toUpperCase())+}++function isEditableItem(item) {+ return Boolean(item && typeof item === 'object' && !Array.isArray(item))+}++function fieldTargetTab(errorPath) {+ return errorPath === 'logic' || errorPath?.startsWith('logic.')+ ? 'logic'+ : 'options'+}++export function normalizeFormSaveErrors(validationResponse, properties = [], computedVariables = []) {+ const fieldGroupsByIndex = new Map()+ const computedVariableGroupsByIndex = new Map()+ const generalErrorsByKey = new Map()+ const responseErrors = validationResponse?.errors++ if (responseErrors && typeof responseErrors === 'object' && !Array.isArray(responseErrors)) {+ Object.entries(responseErrors).forEach(([key, rawMessages]) => {+ const messages = normalizeMessages(rawMessages)+ if (messages.length === 0) {+ return+ }++ const propertyMatch = key.match(/^properties\.(\d+)(?:\.(.+))?$/)+ if (propertyMatch) {+ const fieldIndex = Number(propertyMatch[1])+ const errorPath = propertyMatch[2] || null+ const field = properties[fieldIndex]++ if (!fieldGroupsByIndex.has(fieldIndex)) {+ fieldGroupsByIndex.set(fieldIndex, {+ key: `property:${fieldIndex}`,+ fieldIndex,+ fieldId: field?.id ?? null,+ fieldName: field?.name || `Field ${fieldIndex + 1}`,+ fieldType: field?.type ?? null,+ messages: [],+ targetTab: fieldTargetTab(errorPath),+ canNavigate: isEditableItem(field),+ })+ } else if (fieldTargetTab(errorPath) === 'logic') {+ fieldGroupsByIndex.get(fieldIndex).targetTab = 'logic'+ }++ addUniqueMessages(fieldGroupsByIndex.get(fieldIndex).messages, messages)+ return+ }++ const computedVariableMatch = key.match(/^computed_variables\.(\d+)(?:\.(.+))?$/)+ if (computedVariableMatch) {+ const variableIndex = Number(computedVariableMatch[1])+ const variable = computedVariables[variableIndex]++ if (!computedVariableGroupsByIndex.has(variableIndex)) {+ computedVariableGroupsByIndex.set(variableIndex, {+ key: `computed-variable:${variableIndex}`,+ variableIndex,+ variableId: variable?.id ?? null,+ variableName: variable?.name || `Computed variable ${variableIndex + 1}`,+ messages: [],+ canNavigate: isEditableItem(variable),+ })+ }++ addUniqueMessages(computedVariableGroupsByIndex.get(variableIndex).messages, messages)+ return+ }++ if (!generalErrorsByKey.has(key)) {+ generalErrorsByKey.set(key, {+ key,+ label: humanizeErrorKey(key),+ messages: [],+ })+ }++ addUniqueMessages(generalErrorsByKey.get(key).messages, messages)+ })+ }++ const fieldGroups = Array.from(fieldGroupsByIndex.values())+ const computedVariableGroups = Array.from(computedVariableGroupsByIndex.values())+ const generalErrors = Array.from(generalErrorsByKey.values())+ const issueCount = fieldGroups.length + computedVariableGroups.length + generalErrors.length++ return {+ fieldGroups,+ computedVariableGroups,+ generalErrors,+ issueCount,+ fieldCount: fieldGroups.length,+ computedVariableCount: computedVariableGroups.length,+ fallbackMessage: issueCount === 0+ ? validationResponse?.message || 'An unknown validation error occurred.'+ : null,+ }+}diff --git a/client/stores/working_form.js b/client/stores/working_form.jsindex beec5ed2b..43938ade4 100644--- a/client/stores/working_form.js+++ b/client/stores/working_form.js@@ -14,6 +14,7 @@ export const useWorkingFormStore = defineStore("working_form", {// Field being editedselectedFieldIndex: null,+ selectedFieldTab: 'options',showEditFieldSidebar: null,showAddFieldSidebar: null,blockForm: null,@@ -103,9 +104,15 @@ export const useWorkingFormStore = defineStore("working_form", {setEditingField(field) {this.selectedFieldIndex = this.objectToIndex(field)},- openSettingsForField(field, triggerBounce = false) {+ openSettingsForField(field, triggerBounce = false, targetTab = null) {const targetIndex = this.objectToIndex(field)const previousIndex = this.selectedFieldIndex++ if (targetTab) {+ this.selectedFieldTab = targetTab+ } else if (targetIndex !== previousIndex || !this.showEditFieldSidebar) {+ this.selectedFieldTab = 'options'+ }// Check if sidebar is already open for the same field and bounce is requestedif (triggerBounce && this.showEditFieldSidebar && targetIndex === previousIndex) {@@ -153,6 +160,7 @@ export const useWorkingFormStore = defineStore("working_form", {reset() {this.content = nullthis.selectedFieldIndex = null+ this.selectedFieldTab = 'options'this.showEditFieldSidebar = falsethis.showAddFieldSidebar = falsethis.blockForm = nulldiff --git a/client/test/e2e/opnform-flows.spec.ts b/client/test/e2e/opnform-flows.spec.tsindex 659cba7d2..e8e567478 100644--- a/client/test/e2e/opnform-flows.spec.ts+++ b/client/test/e2e/opnform-flows.spec.ts@@ -540,6 +540,111 @@ test("editing an existing form title persists after save", async ({ page, requesawait expect(page.getByRole("heading", { name: updatedTitle, exact: true })).toBeVisible()})+test("form save errors open the invalid field section and computed variable", async ({ page, request }) => {+ const form = await apiCreateForm(request, {+ title: uniqueTitle("Save Error Form"),+ payloadOverrides: {+ properties: [+ {+ type: "nf-text",+ content: "<h1>Save error form</h1>",+ name: "Title",+ id: "save_error_title",+ },+ buildTextField("contact_name", "Contact name"),+ buildSelectField("problematic-dropdown", "Problematic dropdown", ["Temporary option"]),+ ],+ computed_variables: [{+ id: "cv_order_total",+ name: "Order total",+ formula: "1 + 1",+ result_type: "number",+ }],+ },+ })++ await loginUi(page)+ let saveAttempt = 0+ await page.route("**/open/forms/*", async (route) => {+ if (route.request().method() !== "PUT") {+ await route.continue()+ return+ }++ saveAttempt += 1++ const responseBody = saveAttempt === 1+ ? {+ message: "At least one option is required. (and 1 more error)",+ errors: {+ "properties.2.select.options": ["At least one option is required."],+ properties: ["One or more properties have validation errors."],+ },+ }+ : saveAttempt === 2+ ? {+ message: "The logic actions for Problematic dropdown are not valid. (and 1 more error)",+ errors: {+ "properties.2.logic": ["The logic actions for Problematic dropdown are not valid."],+ properties: ["One or more properties have validation errors."],+ },+ }+ : {+ message: "The formula is required. (and 1 more error)",+ errors: {+ "computed_variables.0.formula": ["The formula is required."],+ computed_variables: ["One or more computed variables have validation errors."],+ },+ }++ await route.fulfill({+ status: 422,+ contentType: "application/json",+ body: JSON.stringify(responseBody),+ })+ })++ await page.goto(`/forms/${form.slug}/edit`)+ await expect(page.locator("#form-editor")).toBeVisible()+ await page.getByTestId("save-form-button").click()++ const errorModal = page.getByTestId("form-save-error-modal")+ await expect(errorModal).toBeVisible()+ await expect(page.getByText("Fix 1 field before saving", { exact: true })).toBeVisible()+ await expect(errorModal).toContainText("Problematic dropdown")+ await expect(errorModal).toContainText("At least one option is required.")+ await expect(errorModal).not.toContainText("One or more properties have validation errors.")+ await expect(errorModal).not.toContainText("and 1 more error")++ await page.getByTestId("edit-form-field-problematic-dropdown").click()++ await expect(errorModal).toBeHidden()+ const fieldSettings = page.getByTestId("form-field-settings")+ await expect(fieldSettings).toBeVisible()+ await expect(fieldSettings).toBeFocused()+ await expect(fieldSettings).toContainText("Select Options")++ await page.getByTestId("save-form-button").click()+ await expect(errorModal).toBeVisible()+ await expect(errorModal).toContainText("The logic actions for Problematic dropdown are not valid.")+ await page.getByTestId("edit-form-field-problematic-dropdown").click()++ await expect(errorModal).toBeHidden()+ await expect(fieldSettings).toContainText("When following condition(s) are true")++ await page.getByTestId("save-form-button").click()+ await expect(errorModal).toBeVisible()+ await expect(page.getByText("Fix 1 variable before saving", { exact: true })).toBeVisible()+ await expect(errorModal).toContainText("Order total")+ await expect(errorModal).toContainText("The formula is required.")+ await page.getByTestId("edit-computed-variable-cv_order_total").click()++ const variableModal = page.getByTestId("computed-variable-modal")+ await expect(variableModal).toBeVisible()+ await expect(variableModal.getByText("Edit Variable", { exact: true })).toBeVisible()+ await expect(variableModal.getByPlaceholder("e.g., Total Price, Dog Age")).toHaveValue("Order total")+})+test("public submissions are accepted and visible in the submissions dashboard", async ({ page, request }) => {const form = await apiCreateForm(request, { title: uniqueTitle("Submission Form") })const { visitorName, visitorEmail } = await submitPublicForm(page, form.slug)diff --git a/client/test/nuxt/form-error-modal.spec.ts b/client/test/nuxt/form-error-modal.spec.tsnew file mode 100644index 000000000..54559b0ed--- /dev/null+++ b/client/test/nuxt/form-error-modal.spec.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from 'vitest'+import { mount } from '@vue/test-utils'+import FormErrorModal from '~/components/open/forms/components/form-components/FormErrorModal.vue'++const fieldError = {+ key: 'property:2',+ fieldIndex: 2,+ fieldId: 'pride-list',+ fieldName: 'siehe Pride-Liste',+ fieldType: 'select',+ messages: ['At least one option is required.'],+ targetTab: 'options',+ canNavigate: true,+}++const computedVariableError = {+ key: 'computed-variable:1',+ variableIndex: 1,+ variableId: 'cv_tax',+ variableName: 'Tax',+ messages: ['The formula is required.'],+ canNavigate: true,+}++function createWrapper(errorSummary = {}) {+ return mount(FormErrorModal, {+ props: {+ show: true,+ errorSummary: {+ fieldGroups: [],+ computedVariableGroups: [],+ generalErrors: [],+ issueCount: 0,+ fieldCount: 0,+ computedVariableCount: 0,+ fallbackMessage: null,+ ...errorSummary,+ },+ },+ global: {+ stubs: {+ UModal: {+ props: ['open', 'title', 'ui'],+ emits: ['update:open'],+ template: '<div class="modal"><h2>{{ title }}</h2><slot name="body" /><slot name="footer" /></div>',+ },+ UButton: {+ emits: ['click'],+ template: '<button @click="$emit(\'click\')"><slot /></button>',+ },+ Icon: {+ template: '<span />',+ },+ },+ },+ })+}++describe('FormErrorModal', () => {+ it('identifies a single invalid field without showing aggregate API errors', () => {+ const wrapper = createWrapper({+ fieldGroups: [fieldError],+ issueCount: 1,+ fieldCount: 1,+ })++ expect(wrapper.get('h2').text()).toBe('Fix 1 field before saving')+ expect(wrapper.text()).toContain('siehe Pride-Liste')+ expect(wrapper.text()).toContain('Select')+ expect(wrapper.text()).toContain('At least one option is required.')+ expect(wrapper.text()).not.toContain('One or more properties have validation errors.')+ expect(wrapper.text()).not.toContain('and 1 more error')+ })++ it('uses a plural field count when multiple fields are invalid', () => {+ const wrapper = createWrapper({+ fieldGroups: [+ fieldError,+ {+ ...fieldError,+ key: 'property:3',+ fieldIndex: 3,+ fieldId: 'email',+ fieldName: 'Email',+ fieldType: 'email',+ },+ ],+ issueCount: 2,+ fieldCount: 2,+ })++ expect(wrapper.get('h2').text()).toBe('Fix 2 fields before saving')+ })++ it('emits the selected field when Edit field is clicked', async () => {+ const wrapper = createWrapper({+ fieldGroups: [fieldError],+ issueCount: 1,+ fieldCount: 1,+ })++ const editButton = wrapper.get('[data-testid="edit-form-field-pride-list"]')+ expect(editButton.attributes('aria-label')).toBe('Edit siehe Pride-Liste')++ await editButton.trigger('click')++ expect(wrapper.emitted('edit-field')).toEqual([[fieldError]])+ })++ it('shows field and general errors as separate issues', () => {+ const wrapper = createWrapper({+ fieldGroups: [fieldError],+ generalErrors: [{+ key: 'title',+ label: 'Title',+ messages: ['The title field is required.'],+ }],+ issueCount: 2,+ fieldCount: 1,+ })++ expect(wrapper.get('h2').text()).toBe('Fix 2 issues before saving')+ expect(wrapper.get('[data-testid="form-save-general-errors"]').text())+ .toContain('The title field is required.')+ })++ it('identifies a computed variable and emits it for editing', async () => {+ const wrapper = createWrapper({+ computedVariableGroups: [computedVariableError],+ issueCount: 1,+ computedVariableCount: 1,+ })++ expect(wrapper.get('h2').text()).toBe('Fix 1 variable before saving')+ expect(wrapper.text()).toContain('Tax')+ expect(wrapper.text()).toContain('The formula is required.')++ const editButton = wrapper.get('[data-testid="edit-computed-variable-cv_tax"]')+ expect(editButton.attributes('aria-label')).toBe('Edit Tax')++ await editButton.trigger('click')++ expect(wrapper.emitted('edit-computed-variable')).toEqual([[computedVariableError]])+ })++ it('shows a safe fallback when no structured errors are available', () => {+ const wrapper = createWrapper({+ fallbackMessage: 'Unable to validate the form.',+ })++ expect(wrapper.get('h2').text()).toBe("We couldn't save your form")+ expect(wrapper.text()).toContain('Unable to validate the form.')+ })++ it('exposes the error summary as an assertive alert', () => {+ const wrapper = createWrapper({+ fieldGroups: [fieldError],+ issueCount: 1,+ fieldCount: 1,+ })++ const alert = wrapper.get('[data-testid="form-save-error-modal"]')+ expect(alert.attributes('role')).toBe('alert')+ expect(alert.attributes('aria-live')).toBe('assertive')+ })+})diff --git a/client/test/unit/form-save-errors.test.ts b/client/test/unit/form-save-errors.test.tsnew file mode 100644index 000000000..147935b46--- /dev/null+++ b/client/test/unit/form-save-errors.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from 'vitest'+import { normalizeFormSaveErrors } from '../../lib/forms/form-save-errors.js'++const properties = [+ { id: 'title', name: 'Title', type: 'nf-text' },+ { id: 'email', name: 'Email', type: 'email' },+ { id: 'pride-list', name: 'siehe Pride-Liste', type: 'select' },+]++const computedVariables = [+ { id: 'cv_total', name: 'Order total', formula: '1 + 1' },+ { id: 'cv_tax', name: 'Tax', formula: '2' },+]++describe('normalizeFormSaveErrors', () => {+ it('maps a property validation error to its form field', () => {+ const summary = normalizeFormSaveErrors({+ message: 'At least one option is required. (and 1 more error)',+ errors: {+ 'properties.2.select.options': ['At least one option is required.'],+ properties: ['One or more properties have validation errors.'],+ },+ }, properties)++ expect(summary).toMatchObject({+ fieldCount: 1,+ issueCount: 1,+ generalErrors: [],+ fallbackMessage: null,+ })+ expect(summary.fieldGroups[0]).toEqual({+ key: 'property:2',+ fieldIndex: 2,+ fieldId: 'pride-list',+ fieldName: 'siehe Pride-Liste',+ fieldType: 'select',+ messages: ['At least one option is required.'],+ targetTab: 'options',+ canNavigate: true,+ })+ })++ it('groups and deduplicates multiple messages for the same field', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ 'properties.2.select.options': [+ 'At least one option is required.',+ 'At least one option is required.',+ ],+ 'properties.2.option_display_mode': 'The option display mode is invalid.',+ },+ }, properties)++ expect(summary.fieldGroups).toHaveLength(1)+ expect(summary.fieldGroups[0].messages).toEqual([+ 'At least one option is required.',+ 'The option display mode is invalid.',+ ])+ })++ it('keeps errors from different fields separate', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ 'properties.1.name': ['The field name is required.'],+ 'properties.2.select.options': ['At least one option is required.'],+ },+ }, properties)++ expect(summary.fieldGroups.map(group => group.fieldName)).toEqual([+ 'Email',+ 'siehe Pride-Liste',+ ])+ expect(summary.issueCount).toBe(2)+ })++ it('targets the logic tab when a field logic error is returned', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ 'properties.1.logic': ['The logic actions for Email are not valid.'],+ },+ }, properties)++ expect(summary.fieldGroups[0]).toMatchObject({+ fieldId: 'email',+ targetTab: 'logic',+ })+ })++ it('keeps useful general errors alongside field errors', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ title: ['The title field is required.'],+ 'properties.2.select.options': ['At least one option is required.'],+ },+ }, properties)++ expect(summary.generalErrors).toEqual([{+ key: 'title',+ label: 'Title',+ messages: ['The title field is required.'],+ }])+ expect(summary.issueCount).toBe(2)+ })++ it('falls back safely when the property index cannot be resolved', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ 'properties.9.type': ['The field type is required.'],+ },+ }, properties)++ expect(summary.fieldGroups[0]).toMatchObject({+ fieldIndex: 9,+ fieldId: null,+ fieldName: 'Field 10',+ fieldType: null,+ canNavigate: false,+ })+ })++ it('preserves substantive computed variable errors while removing the aggregate message', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ computed_variables: [+ 'Circular dependency detected between Total and Tax.',+ 'One or more computed variables have validation errors.',+ ],+ },+ }, properties)++ expect(summary.generalErrors).toEqual([{+ key: 'computed_variables',+ label: 'Computed variables',+ messages: ['Circular dependency detected between Total and Tax.'],+ }])+ })++ it('groups indexed computed variable errors with the variable identity', () => {+ const summary = normalizeFormSaveErrors({+ errors: {+ 'computed_variables.1.id': ['Duplicate computed variable ID.'],+ 'computed_variables.1.formula': ['The formula is required.'],+ computed_variables: ['One or more computed variables have validation errors.'],+ },+ }, properties, computedVariables)++ expect(summary.computedVariableGroups).toEqual([{+ key: 'computed-variable:1',+ variableIndex: 1,+ variableId: 'cv_tax',+ variableName: 'Tax',+ messages: ['Duplicate computed variable ID.', 'The formula is required.'],+ canNavigate: true,+ }])+ expect(summary).toMatchObject({+ computedVariableCount: 1,+ issueCount: 1,+ generalErrors: [],+ })+ })++ it('uses the response message only when no structured error remains', () => {+ const summary = normalizeFormSaveErrors({+ message: 'Unable to validate the form.',+ errors: {+ properties: ['One or more properties have validation errors.'],+ },+ }, properties)++ expect(summary).toMatchObject({+ fieldGroups: [],+ generalErrors: [],+ issueCount: 0,+ fallbackMessage: 'Unable to validate the form.',+ })+ })++ it('provides a safe fallback for a malformed response', () => {+ expect(normalizeFormSaveErrors(null, properties).fallbackMessage)+ .toBe('An unknown validation error occurred.')+ })+})