Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFR] Fix Form Become Dirty After Record Initialization #3721

Merged
merged 2 commits into from
Sep 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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