From 489626bc3ced1564e3fb7306be8aad98af6ba5a3 Mon Sep 17 00:00:00 2001 From: Jan-Gerke Salomon Date: Mon, 30 Oct 2023 17:02:59 +0100 Subject: [PATCH] fix(de form fields): ignore "itself" when validating uniqueness --- src/pages/dataElements/form/fields.tsx | 15 +++++++++-- .../form/useIsFieldValueUnique.ts | 26 +++++++++++++------ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/pages/dataElements/form/fields.tsx b/src/pages/dataElements/form/fields.tsx index 7f85ccba..ff727c76 100644 --- a/src/pages/dataElements/form/fields.tsx +++ b/src/pages/dataElements/form/fields.tsx @@ -12,6 +12,7 @@ import { import React, { useRef } from 'react' import { Field as FieldRFF, useField } from 'react-final-form' import { useHref } from 'react-router' +import { useParams } from 'react-router-dom' import { AggregationLevelMultiSelect, ColorAndIconPicker, @@ -26,8 +27,13 @@ import { EditableFieldWrapper } from './EditableFieldWrapper' import { useIsFieldValueUnique } from './useIsFieldValueUnique' export function NameField() { + const params = useParams() + const dataElementId = params.id as string + const checkIsValueTaken = useIsFieldValueUnique({ + field: 'name', + id: dataElementId, + }) const { meta } = useField('name') - const checkIsValueTaken = useIsFieldValueUnique('name') return ( ) => ({ - pageSize: 1, - fields: 'id', - filter: [`${variables.field}:eq:${variables.value}`], - }), + params: (variables: Record) => { + const filter = [`${variables.field}:eq:${variables.value}`] + + if (variables.id) { + filter.push(`id:ne:${variables.id}`) + } + + return { pageSize: 1, fields: 'id', filter } + }, }, } @@ -22,7 +26,13 @@ interface QueryResponse { } } -export function useIsFieldValueUnique(field: string) { +export function useIsFieldValueUnique({ + field, + id, +}: { + field: string + id: string +}) { const engine = useDataEngine() const validate = useMemo( @@ -33,7 +43,7 @@ export function useIsFieldValueUnique(field: string) { } const data = (await engine.query(HAS_FIELD_VALUE_QUERY, { - variables: { field, value }, + variables: { field, value, id }, })) as unknown as QueryResponse if (data.dataElements.pager.total > 0) { @@ -42,7 +52,7 @@ export function useIsFieldValueUnique(field: string) { ) } }), - [field, engine] + [field, engine, id] ) return useDebouncedCallback(validate, 200, { leading: true })