Skip to content

Commit 4eebf3c

Browse files
authored
Merge pull request #8204 from marmelab/fix-simpleforminterator
Fix `SimpleFormIterator` defaultValues when adding a record
2 parents c03fdf2 + 3ec60db commit 4eebf3c

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

packages/ra-ui-materialui/src/input/ArrayInput/SimpleFormIterator.tsx

+14-2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
ReactNode,
99
useCallback,
1010
useMemo,
11+
useRef,
1112
} from 'react';
1213
import { styled, SxProps } from '@mui/material';
1314
import clsx from 'clsx';
@@ -49,6 +50,7 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
4950
} = props;
5051
const { append, fields, move, remove } = useArrayInput(props);
5152
const record = useRecordContext(props);
53+
const initialDefaultValue = useRef({});
5254

5355
const removeField = useCallback(
5456
(index: number) => {
@@ -57,10 +59,18 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
5759
[remove]
5860
);
5961

62+
if (fields.length > 0) {
63+
const { id, ...rest } = fields[0];
64+
initialDefaultValue.current = rest;
65+
for (const k in initialDefaultValue.current)
66+
initialDefaultValue.current[k] = '';
67+
}
68+
6069
const addField = useCallback(
6170
(item: any = undefined) => {
6271
let defaultValue = item;
6372
if (item == null) {
73+
defaultValue = initialDefaultValue.current;
6474
if (
6575
Children.count(children) === 1 &&
6676
React.isValidElement(Children.only(children)) &&
@@ -73,11 +83,13 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
7383
} else {
7484
// ArrayInput used for an array of objects
7585
// (e.g. authors: [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Jane', lastName: 'Doe' }])
76-
defaultValue = {} as Record<string, unknown>;
86+
defaultValue =
87+
defaultValue || ({} as Record<string, unknown>);
7788
Children.forEach(children, input => {
7889
if (
7990
React.isValidElement(input) &&
80-
input.type !== FormDataConsumer
91+
input.type !== FormDataConsumer &&
92+
input.props.source
8193
) {
8294
defaultValue[input.props.source] =
8395
input.props.defaultValue ?? '';

0 commit comments

Comments
 (0)