Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 77df9ca

Browse files
committed
Extend getFormHelpers to remap field name
1 parent 680898f commit 77df9ca

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

site/src/components/WorkspaceScheduleForm/WorkspaceScheduleForm.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ export const WorkspaceScheduleForm: FC<WorkspaceScheduleFormProps> = ({
266266
</FormControl>
267267

268268
<TextField
269-
{...formHelpers("ttl", ttlShutdownAt(form.values.ttl))}
269+
{...formHelpers("ttl", ttlShutdownAt(form.values.ttl), "ttl_ms")}
270270
disabled={isLoading}
271271
inputProps={{ min: 0, step: 1 }}
272272
label={Language.ttlLabel}

site/src/util/formUtils.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,21 @@ interface FormHelpers {
2525
helperText?: ReactNode
2626
}
2727

28+
// backendErrorName can be used if the backend names a field differently than the frontend does
2829
export const getFormHelpers =
29-
<T>(form: FormikContextType<T>, formErrors?: FormikErrors<T>) =>
30-
(name: keyof T, HelperText: ReactNode = ""): FormHelpers => {
30+
<T>(form: FormikContextType<T>, apiValidationErrors?: FormikErrors<T>) =>
31+
(name: keyof T, HelperText: ReactNode = "", backendErrorName?: string): FormHelpers => {
3132
if (typeof name !== "string") {
3233
throw new Error(`name must be type of string, instead received '${typeof name}'`)
3334
}
35+
const apiErrorName = backendErrorName ?? name
3436

3537
// getIn is a util function from Formik that gets at any depth of nesting
3638
// and is necessary for the types to work
3739
const touched = getIn(form.touched, name)
38-
const apiError = getIn(formErrors, name)
39-
const validationError = getIn(form.errors, name)
40-
const error = apiError ?? validationError
40+
const apiError = getIn(apiValidationErrors, apiErrorName)
41+
const frontendError = getIn(form.errors, name)
42+
const error = apiError ?? frontendError
4143
return {
4244
...form.getFieldProps(name),
4345
id: name,
@@ -49,7 +51,7 @@ export const getFormHelpers =
4951
export const getFormHelpersWithError = <T>(
5052
form: FormikContextType<T>,
5153
error?: Error | unknown,
52-
): ((name: keyof T, HelperText?: ReactNode) => FormHelpers) => {
54+
): ((name: keyof T, HelperText?: ReactNode, errorName?: string) => FormHelpers) => {
5355
const apiValidationErrors =
5456
isApiError(error) && hasApiFieldErrors(error)
5557
? (mapApiErrorToFieldErrors(error.response.data) as FormikErrors<T>)

0 commit comments

Comments
 (0)