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 ArrayInput Does Not Apply Default Values Set On Inputs #9198

Merged
merged 1 commit into from
Aug 18, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ describe('<SimpleFormIterator />', () => {
screen
.queryAllByLabelText('Email')
.map(inputElement => (inputElement as HTMLInputElement).value)
).toEqual(['']);
).toEqual(['default@marmelab.com']);
expect(
screen
.queryAllByLabelText('Name')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
useRecordContext,
useTranslate,
} from 'ra-core';
import { UseFieldArrayReturn } from 'react-hook-form';
import { UseFieldArrayReturn, useFormContext } from 'react-hook-form';

import { useArrayInput } from './useArrayInput';
import {
Expand Down Expand Up @@ -60,6 +60,7 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
} = props;
const [confirmIsOpen, setConfirmIsOpen] = useState<boolean>(false);
const { append, fields, move, remove, replace } = useArrayInput(props);
const { resetField } = useFormContext();
const translate = useTranslate();
const record = useRecordContext(props);
const initialDefaultValue = useRef({});
Expand Down Expand Up @@ -117,8 +118,10 @@ export const SimpleFormIterator = (props: SimpleFormIteratorProps) => {
}
}
append(defaultValue);
// Make sure the newly added inputs are not considered dirty by react-hook-form
resetField(`${source}.${fields.length}`, { defaultValue });
},
[append, children]
[append, children, resetField, source, fields.length]
);

// add field and call the onClick event of the button passed as addButton prop
Expand Down
25 changes: 24 additions & 1 deletion packages/ra-ui-materialui/src/input/SelectArrayInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import { AdminContext } from '../AdminContext';
import { SimpleForm } from '../form';
import { SelectArrayInput } from './SelectArrayInput';
import { useCreateSuggestionContext } from './useSupportCreateSuggestion';
import { DifferentIdTypes, TranslateChoice } from './SelectArrayInput.stories';
import {
DifferentIdTypes,
TranslateChoice,
InsideArrayInput,
} from './SelectArrayInput.stories';

describe('<SelectArrayInput />', () => {
const defaultProps = {
Expand Down Expand Up @@ -636,4 +640,23 @@ describe('<SelectArrayInput />', () => {
);
expect(screen.queryByTestId('selectArray')).toBeDefined();
});

it('should always apply its default value inside an ArrayInput', async () => {
render(<InsideArrayInput />);
await screen.findByText('Foo');
fireEvent.click(screen.getByLabelText('Remove'));
await waitFor(() => {
expect(screen.queryByText('Foo')).toBeNull();
});
fireEvent.click(screen.getByLabelText('Add'));
await screen.findByText('Foo');
fireEvent.click(screen.getByLabelText('Remove'));
await waitFor(() => {
expect(screen.queryByText('Foo')).toBeNull();
});
fireEvent.click(screen.getByLabelText('Add'));
await screen.findByText('Foo');
fireEvent.click(screen.getByLabelText('Add'));
expect(await screen.findAllByText('Foo')).toHaveLength(2);
});
});
71 changes: 71 additions & 0 deletions packages/ra-ui-materialui/src/input/SelectArrayInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,26 @@ import { SelectArrayInput } from './SelectArrayInput';
import { ReferenceArrayInput } from './ReferenceArrayInput';
import { useCreateSuggestionContext } from './useSupportCreateSuggestion';
import { TextInput } from './TextInput';
import { ArrayInput, SimpleFormIterator } from './ArrayInput';
import { FormDataConsumer } from 'ra-core';
import { useWatch } from 'react-hook-form';

export default { title: 'ra-ui-materialui/input/SelectArrayInput' };

const i18nProvider = polyglotI18nProvider(() => englishMessages);

const FormInspector = ({ source }) => {
const value = useWatch({ name: source });
return (
<div style={{ backgroundColor: 'lightgrey' }}>
{source} value in form:&nbsp;
<code>
{JSON.stringify(value)} ({typeof value})
</code>
</div>
);
};

export const Basic = () => (
<AdminContext i18nProvider={i18nProvider}>
<Create
Expand Down Expand Up @@ -67,6 +82,62 @@ export const Basic = () => (
</AdminContext>
);

export const DefaultValue = () => (
<AdminContext i18nProvider={i18nProvider}>
<Create resource="users" sx={{ width: 600 }}>
<SimpleForm>
<SelectArrayInput
source="roles"
defaultValue={['u001', 'u003']}
choices={[
{ id: 'admin', name: 'Admin' },
{ id: 'u001', name: 'Editor' },
{ id: 'u002', name: 'Moderator' },
{ id: 'u003', name: 'Reviewer' },
]}
sx={{ width: 300 }}
/>
</SimpleForm>
</Create>
</AdminContext>
);

export const InsideArrayInput = () => (
<AdminContext i18nProvider={i18nProvider}>
<Create resource="users" sx={{ width: 600 }}>
<SimpleForm>
<ArrayInput
source="items"
label="Items"
defaultValue={[{ data: ['foo'] }]}
>
<SimpleFormIterator>
<FormDataConsumer>
{({ getSource }) => {
const source = getSource!('data');
return (
<>
<SelectArrayInput
label="data"
source={source}
choices={[
{ id: 'foo', name: 'Foo' },
{ id: 'bar', name: 'Bar' },
]}
defaultValue={['foo']}
/>
</>
);
}}
</FormDataConsumer>
</SimpleFormIterator>
</ArrayInput>
<FormInspector source="items" />
</SimpleForm>
</Create>
</AdminContext>
);

const choices = [
{ id: 'admin', name: 'Admin' },
{ id: 'u001', name: 'Editor' },
Expand Down