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

Fix SimpleFormIterator defaultValues when adding a record #8204

Merged
merged 5 commits into from
Sep 29, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
ReactNode,
useCallback,
useMemo,
useRef,
} from 'react';
import { styled, SxProps } from '@mui/material';
import clsx from 'clsx';
Expand Down Expand Up @@ -49,6 +50,7 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
} = props;
const { append, fields, move, remove } = useArrayInput(props);
const record = useRecordContext(props);
const initialDefaultValue = useRef({});

const removeField = useCallback(
(index: number) => {
Expand All @@ -57,10 +59,18 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
[remove]
);

if (fields.length > 0) {
const { id, ...rest } = fields[0];
initialDefaultValue.current = rest;
for (const k in initialDefaultValue.current)
initialDefaultValue.current[k] = '';
}

const addField = useCallback(
(item: any = undefined) => {
let defaultValue = item;
if (item == null) {
defaultValue = initialDefaultValue.current;
if (
Children.count(children) === 1 &&
React.isValidElement(Children.only(children)) &&
Expand All @@ -73,11 +83,13 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
} else {
// ArrayInput used for an array of objects
// (e.g. authors: [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Jane', lastName: 'Doe' }])
defaultValue = {} as Record<string, unknown>;
defaultValue =
defaultValue || ({} as Record<string, unknown>);
Children.forEach(children, input => {
if (
React.isValidElement(input) &&
input.type !== FormDataConsumer
input.type !== FormDataConsumer &&
input.props.source
) {
defaultValue[input.props.source] =
input.props.defaultValue ?? '';
Expand Down