Skip to content

Commit

Permalink
Merge pull request #3721 from marmelab/fix-forms-dirty-state-after-re…
Browse files Browse the repository at this point in the history
…cord-initialization

[RFR] Fix Form Become Dirty After Record Initialization
  • Loading branch information
fzaninotto authored Sep 20, 2019
2 parents cbdaaa2 + 7ecbc8a commit 171e0d3
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
16 changes: 13 additions & 3 deletions packages/ra-core/src/form/useInitializeFormWithRecord.ts
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion packages/ra-ui-materialui/src/form/SimpleForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ const SimpleFormView = ({
margin,
...rest
}) => {
useInitializeFormWithRecord(form, record);
useInitializeFormWithRecord(record);

const handleSubmitWithRedirect = useCallback(
(redirect = defaultRedirect) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/ra-ui-materialui/src/form/TabbedForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export const TabbedFormView = ({
margin,
...rest
}) => {
useInitializeFormWithRecord(form, record);
useInitializeFormWithRecord(record);

const handleSubmitWithRedirect = useCallback(
(redirect = defaultRedirect) => {
Expand Down

0 comments on commit 171e0d3

Please sign in to comment.