Skip to content

Commit

Permalink
Fix Form Initialization from Record
Browse files Browse the repository at this point in the history
  • Loading branch information
djhi committed Aug 12, 2020
1 parent 9d568a8 commit 1373500
Showing 1 changed file with 4 additions and 37 deletions.
41 changes: 4 additions & 37 deletions packages/ra-core/src/form/useInitializeFormWithRecord.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect } from 'react';
import { useForm } from 'react-final-form';
import { isObject } from '../inference/assertions';
import { merge } from 'lodash';

/**
* Restore the record values which should override any default values specified on the form.
Expand All @@ -13,42 +13,9 @@ const useInitializeFormWithRecord = 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 => {
// We have to check that 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)) {
if (Array.isArray(record[key])) {
// array of values
record[key].forEach((value, index) => {
if (
isObject(value) &&
Object.keys(value).length > 0
) {
// array of objects
Object.keys(value).forEach(key2 => {
form.change(
`${key}[${index}].${key2}`,
value[key2]
);
});
} else {
// array of scalar values
form.change(`${key}[${index}]`, value);
}
});
} else {
// scalar value
form.change(key, record[key]);
}
form.resetFieldState(key);
}
});
});
const initialValues = form.getState().initialValues;
const initialValuesMergedWithRecord = merge({}, initialValues, record);
form.initialize(initialValuesMergedWithRecord);
}, [form, JSON.stringify(record)]); // eslint-disable-line react-hooks/exhaustive-deps
};

Expand Down

0 comments on commit 1373500

Please sign in to comment.