Skip to content

Commit

Permalink
feat(de name shortname inputs): add uniqueness validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammer5 committed Oct 30, 2023
1 parent 4473cef commit 219fc63
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/pages/dataElements/form/fields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,18 @@ import { AGGREGATION_TYPE, DOMAIN_TYPE, VALUE_TYPE } from '../../../constants'
import { useSchemas } from '../../../lib'
import classes from './customFields.module.css'
import { EditableFieldWrapper } from './EditableFieldWrapper'
import { useHasFieldValue } from './useHasFieldValue'

export function NameField() {
const {
loading,
fetching,
refetch: checkIsValueTaken,
} = useHasFieldValue('name')

return (
<FieldRFF
loading={loading || fetching}
component={InputFieldFF}
dataTest="dataelementsformfields-name"
required
Expand All @@ -38,13 +46,21 @@ export function NameField() {
helpText={i18n.t(
'A data element name should be concise and easy to recognize.'
)}
validate={checkIsValueTaken}
/>
)
}

export function ShortNameField() {
const {
loading,
fetching,
refetch: checkIsValueTaken,
} = useHasFieldValue('shortName')

return (
<FieldRFF
loading={loading || fetching}
component={InputFieldFF}
dataTest="dataelementsformfields-shortname"
required
Expand All @@ -54,6 +70,7 @@ export function ShortNameField() {
})}
name="shortName"
helpText={i18n.t('Often used in reports where space is limited')}
validate={checkIsValueTaken}
/>
)
}
Expand Down
53 changes: 53 additions & 0 deletions src/pages/dataElements/form/useHasFieldValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { useDataQuery } from '@dhis2/app-runtime'
import i18n from '@dhis2/d2-i18n'
import { useMemo } from 'react'
import { Pager } from '../../../types/generated'

const HAS_FIELD_VALUE_QUERY = {
dataElements: {
resource: 'dataElements',
params: (variables: Record<string, string>) => ({
pageSize: 1,
fields: '',
filter: [`${variables.field}:eq:${variables.value}`],
}),
},
}

interface QueryResponse {
dataElements: {
pager: Pager
}
}

export function useHasFieldValue(field: string) {
const queryResult = useDataQuery<QueryResponse>(HAS_FIELD_VALUE_QUERY, {
lazy: true,
})

return useMemo(
() => ({
...queryResult,
refetch: (value: string) => {
if (!value) {
return
}

return queryResult.refetch({ field, value }).then(
// We don't have access to app-runtime's internal type `JsonMap`,
// so we have to ignore the type error
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(data: QueryResponse) =>
data.dataElements.pager.total
? i18n.t(
'This {{field}} already exists, please choose antoher one',
{ field }
)
: undefined
)
},
}),
[field, queryResult]
)
}

0 comments on commit 219fc63

Please sign in to comment.