fix: reset field when its deps are not satisfied
This commit is contained in:
@@ -9,12 +9,13 @@ interface ControlledAutocompleteProps extends AutocompleteProps<IFieldDropdownOp
|
|||||||
name: string;
|
name: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
dependsOn?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const getOption = (options: readonly IFieldDropdownOption[], value: string) => options.find(option => option.value === value) || null;
|
const getOption = (options: readonly IFieldDropdownOption[], value: string) => options.find(option => option.value === value) || null;
|
||||||
|
|
||||||
function ControlledAutocomplete(props: ControlledAutocompleteProps): React.ReactElement {
|
function ControlledAutocomplete(props: ControlledAutocompleteProps): React.ReactElement {
|
||||||
const { control } = useFormContext();
|
const { control, watch, setValue, resetField } = useFormContext();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
required = false,
|
required = false,
|
||||||
@@ -25,9 +26,26 @@ function ControlledAutocomplete(props: ControlledAutocompleteProps): React.React
|
|||||||
onChange,
|
onChange,
|
||||||
description,
|
description,
|
||||||
options = [],
|
options = [],
|
||||||
|
dependsOn = [],
|
||||||
...autocompleteProps
|
...autocompleteProps
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
|
let dependsOnValues: unknown[] = [];
|
||||||
|
if (dependsOn?.length) {
|
||||||
|
dependsOnValues = watch(dependsOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const hasDependencies = dependsOnValues.length;
|
||||||
|
const allDepsSatisfied = dependsOnValues.every(Boolean);
|
||||||
|
|
||||||
|
if (hasDependencies && !allDepsSatisfied) {
|
||||||
|
// Reset the field if any dependency is not satisfied
|
||||||
|
setValue(name, null);
|
||||||
|
resetField(name);
|
||||||
|
}
|
||||||
|
}, dependsOnValues);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Controller
|
<Controller
|
||||||
rules={{ required }}
|
rules={{ required }}
|
||||||
|
@@ -44,6 +44,7 @@ export default function InputCreator(props: InputCreatorProps): React.ReactEleme
|
|||||||
clickToCopy,
|
clickToCopy,
|
||||||
variables,
|
variables,
|
||||||
type,
|
type,
|
||||||
|
dependsOn,
|
||||||
} = schema;
|
} = schema;
|
||||||
|
|
||||||
const { data, loading } = useDynamicData(stepId, schema);
|
const { data, loading } = useDynamicData(stepId, schema);
|
||||||
@@ -55,6 +56,7 @@ export default function InputCreator(props: InputCreatorProps): React.ReactEleme
|
|||||||
return (
|
return (
|
||||||
<ControlledAutocomplete
|
<ControlledAutocomplete
|
||||||
name={computedName}
|
name={computedName}
|
||||||
|
dependsOn={dependsOn}
|
||||||
fullWidth
|
fullWidth
|
||||||
disablePortal
|
disablePortal
|
||||||
disableClearable={required}
|
disableClearable={required}
|
||||||
|
Reference in New Issue
Block a user