diff --git a/packages/ra-core/src/form/useInitializeFormWithRecord.ts b/packages/ra-core/src/form/useInitializeFormWithRecord.ts index 2dabc249777..77a4828fafb 100644 --- a/packages/ra-core/src/form/useInitializeFormWithRecord.ts +++ b/packages/ra-core/src/form/useInitializeFormWithRecord.ts @@ -1,22 +1,32 @@ import { useEffect } from 'react'; +import { useForm } from 'react-final-form'; /** * Restore the record values which should override any default values specified on the form. */ -const useInitializeFormWithRecord = (form, record) => { +const useInitializeFormWithRecord = record => { + const form = useForm(); + useEffect(() => { if (!record) { return; } + const registeredFields = form.getRegisteredFields(); + // react-final-form does not provide a way to set multiple values in one call. // Using batch ensure we don't get rerenders until all our values are set form.batch(() => { Object.keys(record).forEach(key => { - form.change(key, record[key]); + // We have to check the record key is actually registered as a field + // as some record keys may not have a matching input + if (registeredFields.some(field => field === key)) { + form.change(key, record[key]); + form.resetFieldState(key); + } }); }); - }, []); // eslint-disable-line + }, [form, record]); }; export default useInitializeFormWithRecord; diff --git a/packages/ra-ui-materialui/src/form/SimpleForm.js b/packages/ra-ui-materialui/src/form/SimpleForm.js index 59ffdd77f9b..326a31daaa6 100644 --- a/packages/ra-ui-materialui/src/form/SimpleForm.js +++ b/packages/ra-ui-materialui/src/form/SimpleForm.js @@ -85,7 +85,7 @@ const SimpleFormView = ({ margin, ...rest }) => { - useInitializeFormWithRecord(form, record); + useInitializeFormWithRecord(record); const handleSubmitWithRedirect = useCallback( (redirect = defaultRedirect) => { diff --git a/packages/ra-ui-materialui/src/form/TabbedForm.js b/packages/ra-ui-materialui/src/form/TabbedForm.js index 7e73435dce7..f782162d3a3 100644 --- a/packages/ra-ui-materialui/src/form/TabbedForm.js +++ b/packages/ra-ui-materialui/src/form/TabbedForm.js @@ -104,7 +104,7 @@ export const TabbedFormView = ({ margin, ...rest }) => { - useInitializeFormWithRecord(form, record); + useInitializeFormWithRecord(record); const handleSubmitWithRedirect = useCallback( (redirect = defaultRedirect) => {