Skip to content

The open alternative to Salesforce, designed for AI.

Show validation rule messages under their field in the record creation form (#27840)

Thomas Trompettef6e4784d9c3d
diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInputs.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInputs.tsx
index 39e27757b54..11924ec75c9 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInputs.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInputs.tsx
@@ -5,6 +5,7 @@ import { getFieldMetadataItemGqlFieldName } from '@/object-metadata/utils/getFie
import { FormFieldInput } from '@/object-record/record-field/ui/components/FormFieldInput';
import { getRecordFormFieldInputSettings } from '@/object-record/record-form/utils/getRecordFormFieldInputSettings';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
+import { type ValidationRuleViolation } from '@/validation-rules/types/ValidationRuleViolation';
import { styled } from '@linaria/react';
import { type JsonValue } from 'type-fest';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -15,10 +16,20 @@ const StyledFieldList = styled.div`
gap: ${themeCssVariables.spacing[3]};
`;
+const StyledFieldViolation = styled.div`
+ color: ${themeCssVariables.font.color.danger};
+ font-size: ${themeCssVariables.font.size.xs};
+ margin-top: ${themeCssVariables.spacing[0.5]};
+`;
+
type RecordFormFieldInputsProps = {
objectMetadataItem: EnrichedObjectMetadataItem;
fieldMetadataItems: FieldMetadataItem[];
draftRecord: Partial<ObjectRecord>;
+ validationRuleViolationsByFieldMetadataId?: Record<
+ string,
+ ValidationRuleViolation[]
+ >;
onFieldValueChange: (gqlFieldName: string, value: JsonValue) => void;
onFieldValueClear: (gqlFieldName: string) => void;
};
@@ -27,6 +38,7 @@ export const RecordFormFieldInputs = ({
objectMetadataItem,
fieldMetadataItems,
draftRecord,
+ validationRuleViolationsByFieldMetadataId = {},
onFieldValueChange,
onFieldValueClear,
}: RecordFormFieldInputsProps) => (
@@ -35,18 +47,27 @@ export const RecordFormFieldInputs = ({
const gqlFieldName = getFieldMetadataItemGqlFieldName(fieldMetadataItem);
return (
- <FormFieldInput
- key={fieldMetadataItem.id}
- field={formatFieldMetadataItemAsFieldDefinition({
- field: fieldMetadataItem,
- objectMetadataItem,
- showLabel: true,
- })}
- defaultValue={draftRecord[gqlFieldName]}
- onChange={(value) => onFieldValueChange(gqlFieldName, value)}
- onClear={() => onFieldValueClear(gqlFieldName)}
- settings={getRecordFormFieldInputSettings(fieldMetadataItem.type)}
- />
+ <div key={fieldMetadataItem.id}>
+ <FormFieldInput
+ field={formatFieldMetadataItemAsFieldDefinition({
+ field: fieldMetadataItem,
+ objectMetadataItem,
+ showLabel: true,
+ })}
+ defaultValue={draftRecord[gqlFieldName]}
+ onChange={(value) => onFieldValueChange(gqlFieldName, value)}
+ onClear={() => onFieldValueClear(gqlFieldName)}
+ settings={getRecordFormFieldInputSettings(fieldMetadataItem.type)}
+ />
+ {(
+ validationRuleViolationsByFieldMetadataId[fieldMetadataItem.id] ??
+ []
+ ).map((violation) => (
+ <StyledFieldViolation key={violation.ruleId} role="alert">
+ {violation.message}
+ </StyledFieldViolation>
+ ))}
+ </div>
);
})}
</StyledFieldList>
diff --git a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx
index 8dbda8acd71..96638662a0a 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx
@@ -26,6 +26,7 @@ import { type ValidationRuleViolation } from '@/validation-rules/types/Validatio
import { buildValidationRuleFieldDescriptors } from '@/validation-rules/utils/buildValidationRuleFieldDescriptors';
import { computeDraftValidationRuleViolations } from '@/validation-rules/utils/computeDraftValidationRuleViolations';
import { getValidationRuleViolationsFromError } from '@/validation-rules/utils/getValidationRuleViolationsFromError';
+import { groupValidationRuleViolationsByField } from '@/validation-rules/utils/groupValidationRuleViolationsByField';
import { useAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentState';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
import { useState } from 'react';
@@ -165,10 +166,19 @@ const SidePanelRecordCreationForm = ({
const hiddenFieldsCount = hiddenFieldMetadataItems.length;
- const validationRuleViolations = [
- ...draftValidationRuleViolations,
- ...serverValidationRuleViolations,
- ];
+ const { violationsByFieldMetadataId, recordViolations } =
+ groupValidationRuleViolationsByField({
+ violations: [
+ ...draftValidationRuleViolations,
+ ...serverValidationRuleViolations,
+ ],
+ displayedFieldMetadataIds: [
+ ...visibleFieldMetadataItems,
+ ...(recordCreationFormAreHiddenFieldsShown
+ ? hiddenFieldMetadataItems
+ : []),
+ ].map((fieldMetadataItem) => fieldMetadataItem.id),
+ });
const computeViolations = (draftRecordToCheck: Partial<ObjectRecord>) =>
computeDraftValidationRuleViolations({
@@ -297,6 +307,9 @@ const SidePanelRecordCreationForm = ({
objectMetadataItem={objectMetadataItem}
fieldMetadataItems={visibleFieldMetadataItems}
draftRecord={draftRecord}
+ validationRuleViolationsByFieldMetadataId={
+ violationsByFieldMetadataId
+ }
onFieldValueChange={handleFieldValueChange}
onFieldValueClear={handleFieldValueClear}
/>
@@ -327,14 +340,17 @@ const SidePanelRecordCreationForm = ({
objectMetadataItem={objectMetadataItem}
fieldMetadataItems={hiddenFieldMetadataItems}
draftRecord={draftRecord}
+ validationRuleViolationsByFieldMetadataId={
+ violationsByFieldMetadataId
+ }
onFieldValueChange={handleFieldValueChange}
onFieldValueClear={handleFieldValueClear}
/>
)}
</StyledContent>
- {validationRuleViolations.length > 0 && (
+ {recordViolations.length > 0 && (
<StyledValidationRuleErrors>
- {validationRuleViolations.map((violation) => (
+ {recordViolations.map((violation) => (
<StyledValidationRuleError key={violation.ruleId} role="alert">
{violation.message}
</StyledValidationRuleError>
diff --git a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx
index 02510eaf797..8fa19d16deb 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx
@@ -1,7 +1,7 @@
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
-import { render, screen } from '@testing-library/react';
+import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Provider as JotaiProvider } from 'jotai';
import { type createElement, type Fragment, type ReactNode } from 'react';
@@ -164,23 +164,49 @@ jest.mock(
RecordFormFieldInputs: ({
fieldMetadataItems,
draftRecord,
+ validationRuleViolationsByFieldMetadataId = {},
onFieldValueChange,
}: {
fieldMetadataItems: { id: string; name: string; label: string }[];
draftRecord: Record<string, unknown>;
+ validationRuleViolationsByFieldMetadataId?: Record<
+ string,
+ { ruleId: string; message: string }[]
+ >;
onFieldValueChange: (gqlFieldName: string, value: string) => void;
}) =>
ReactForMock.createElement(
ReactForMock.Fragment,
null,
fieldMetadataItems.map((fieldMetadataItem) =>
- ReactForMock.createElement('input', {
- key: fieldMetadataItem.id,
- 'aria-label': fieldMetadataItem.label,
- value: (draftRecord[fieldMetadataItem.name] as string) ?? '',
- onChange: (event: { target: { value: string } }) =>
- onFieldValueChange(fieldMetadataItem.name, event.target.value),
- }),
+ ReactForMock.createElement(
+ 'div',
+ {
+ key: fieldMetadataItem.id,
+ role: 'group',
+ 'aria-label': `${fieldMetadataItem.label} field`,
+ },
+ ReactForMock.createElement('input', {
+ 'aria-label': fieldMetadataItem.label,
+ value: (draftRecord[fieldMetadataItem.name] as string) ?? '',
+ onChange: (event: { target: { value: string } }) =>
+ onFieldValueChange(
+ fieldMetadataItem.name,
+ event.target.value,
+ ),
+ }),
+ (
+ validationRuleViolationsByFieldMetadataId[
+ fieldMetadataItem.id
+ ] ?? []
+ ).map((violation) =>
+ ReactForMock.createElement(
+ 'div',
+ { key: violation.ruleId, role: 'alert' },
+ violation.message,
+ ),
+ ),
+ ),
),
),
};
@@ -349,7 +375,7 @@ describe('SidePanelRecordCreationFormPage', () => {
expect(screen.getByLabelText('Nickname')).toHaveValue('Big Apple');
});
- it('reveals a hidden field targeted by a validation error and keeps the message', async () => {
+ it('reveals a hidden field targeted by a validation error and shows the message under it', async () => {
const user = userEvent.setup();
mockValidationRules = [NICKNAME_RULE];
@@ -358,14 +384,16 @@ describe('SidePanelRecordCreationFormPage', () => {
await user.click(screen.getByTestId('record-creation-form-create-button'));
- expect(screen.getByRole('alert')).toHaveTextContent(
- 'A company needs a nickname',
- );
+ expect(
+ within(screen.getByRole('group', { name: 'Nickname field' })).getByRole(
+ 'alert',
+ ),
+ ).toHaveTextContent('A company needs a nickname');
expect(screen.getByLabelText('Nickname')).toBeInTheDocument();
expect(settleRecordCreationDraft).not.toHaveBeenCalled();
});
- it('keeps hidden fields collapsed for a validation error on the whole record', async () => {
+ it('keeps hidden fields collapsed and shows a validation error on the whole record below the fields', async () => {
const user = userEvent.setup();
mockValidationRules = [{ ...NICKNAME_RULE, errorFieldMetadataId: null }];
@@ -377,10 +405,11 @@ describe('SidePanelRecordCreationFormPage', () => {
expect(screen.getByRole('alert')).toHaveTextContent(
'A company needs a nickname',
);
+ expect(screen.getByRole('alert').closest('[role="group"]')).toBeNull();
expect(screen.queryByLabelText('Nickname')).not.toBeInTheDocument();
});
- it('reveals a hidden field the server rejected through a validation rule and shows the message in the form', async () => {
+ it('reveals a hidden field the server rejected through a validation rule and shows the message under it', async () => {
const user = userEvent.setup();
settleRecordCreationDraft.mockResolvedValue({
@@ -397,13 +426,15 @@ describe('SidePanelRecordCreationFormPage', () => {
draftRecord: {},
});
expect(screen.getByLabelText('Nickname')).toBeInTheDocument();
- expect(screen.getByRole('alert')).toHaveTextContent(
- 'A company needs a nickname',
- );
+ expect(
+ within(screen.getByRole('group', { name: 'Nickname field' })).getByRole(
+ 'alert',
+ ),
+ ).toHaveTextContent('A company needs a nickname');
expect(mockEnqueueToast).not.toHaveBeenCalled();
});
- it('keeps a message from the server while the user edits, until the next create', async () => {
+ it('keeps a message from the server under its field while the user edits, until the next create', async () => {
const user = userEvent.setup();
settleRecordCreationDraft.mockResolvedValueOnce({
@@ -415,9 +446,11 @@ describe('SidePanelRecordCreationFormPage', () => {
await user.click(screen.getByTestId('record-creation-form-create-button'));
await user.type(screen.getByLabelText('Domain'), 'apple.com');
- expect(screen.getByRole('alert')).toHaveTextContent(
- 'A company needs a nickname',
- );
+ expect(
+ within(screen.getByRole('group', { name: 'Name field' })).getByRole(
+ 'alert',
+ ),
+ ).toHaveTextContent('A company needs a nickname');
await user.click(screen.getByTestId('record-creation-form-create-button'));
diff --git a/packages/twenty-front/src/modules/validation-rules/utils/__tests__/groupValidationRuleViolationsByField.test.ts b/packages/twenty-front/src/modules/validation-rules/utils/__tests__/groupValidationRuleViolationsByField.test.ts
new file mode 100644
index 00000000000..a4d8de7890f
--- /dev/null
+++ b/packages/twenty-front/src/modules/validation-rules/utils/__tests__/groupValidationRuleViolationsByField.test.ts
@@ -0,0 +1,54 @@
+import { groupValidationRuleViolationsByField } from '@/validation-rules/utils/groupValidationRuleViolationsByField';
+
+const TITLE_VIOLATION = {
+ ruleId: 'title-rule',
+ message: 'A task needs a title',
+ fieldMetadataId: 'field-title',
+};
+
+const RECORD_VIOLATION = {
+ ruleId: 'record-rule',
+ message: 'A task needs an assignee or a due date',
+ fieldMetadataId: null,
+};
+
+describe('groupValidationRuleViolationsByField', () => {
+ it('should put a violation under the field it targets when that field is displayed', () => {
+ expect(
+ groupValidationRuleViolationsByField({
+ violations: [TITLE_VIOLATION, RECORD_VIOLATION],
+ displayedFieldMetadataIds: ['field-title'],
+ }),
+ ).toEqual({
+ violationsByFieldMetadataId: { 'field-title': [TITLE_VIOLATION] },
+ recordViolations: [RECORD_VIOLATION],
+ });
+ });
+
+ it('should keep a violation on the record when its field is not displayed', () => {
+ expect(
+ groupValidationRuleViolationsByField({
+ violations: [TITLE_VIOLATION],
+ displayedFieldMetadataIds: ['field-due-date'],
+ }),
+ ).toEqual({
+ violationsByFieldMetadataId: {},
+ recordViolations: [TITLE_VIOLATION],
+ });
+ });
+
+ it('should list every violation of a field', () => {
+ const secondTitleViolation = {
+ ruleId: 'title-length-rule',
+ message: 'A task title needs at least 3 characters',
+ fieldMetadataId: 'field-title',
+ };
+
+ expect(
+ groupValidationRuleViolationsByField({
+ violations: [TITLE_VIOLATION, secondTitleViolation],
+ displayedFieldMetadataIds: ['field-title'],
+ }).violationsByFieldMetadataId,
+ ).toEqual({ 'field-title': [TITLE_VIOLATION, secondTitleViolation] });
+ });
+});
diff --git a/packages/twenty-front/src/modules/validation-rules/utils/groupValidationRuleViolationsByField.ts b/packages/twenty-front/src/modules/validation-rules/utils/groupValidationRuleViolationsByField.ts
new file mode 100644
index 00000000000..a83430b1987
--- /dev/null
+++ b/packages/twenty-front/src/modules/validation-rules/utils/groupValidationRuleViolationsByField.ts
@@ -0,0 +1,45 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ValidationRuleViolation } from '@/validation-rules/types/ValidationRuleViolation';
+
+type GroupedValidationRuleViolations = {
+ violationsByFieldMetadataId: Record<string, ValidationRuleViolation[]>;
+ recordViolations: ValidationRuleViolation[];
+};
+
+export const groupValidationRuleViolationsByField = ({
+ violations,
+ displayedFieldMetadataIds,
+}: {
+ violations: ValidationRuleViolation[];
+ displayedFieldMetadataIds: string[];
+}): GroupedValidationRuleViolations =>
+ violations.reduce<GroupedValidationRuleViolations>(
+ (groupedViolations, violation) => {
+ const { fieldMetadataId } = violation;
+
+ if (
+ !isDefined(fieldMetadataId) ||
+ !displayedFieldMetadataIds.includes(fieldMetadataId)
+ ) {
+ return {
+ ...groupedViolations,
+ recordViolations: [...groupedViolations.recordViolations, violation],
+ };
+ }
+
+ return {
+ ...groupedViolations,
+ violationsByFieldMetadataId: {
+ ...groupedViolations.violationsByFieldMetadataId,
+ [fieldMetadataId]: [
+ ...(groupedViolations.violationsByFieldMetadataId[
+ fieldMetadataId
+ ] ?? []),
+ violation,
+ ],
+ },
+ };
+ },
+ { violationsByFieldMetadataId: {}, recordViolations: [] },
+ );