diff --git a/.changeset/itchy-stingrays-smell.md b/.changeset/itchy-stingrays-smell.md new file mode 100644 index 00000000000..de5c245690c --- /dev/null +++ b/.changeset/itchy-stingrays-smell.md @@ -0,0 +1,5 @@ +--- +"@talend/react-forms": patch +--- + +Forms: array widget - use default value when add new item diff --git a/packages/forms/src/UIForm/fieldsets/Array/Array.component.js b/packages/forms/src/UIForm/fieldsets/Array/Array.component.js index 978a3e9dcdd..511e4443de7 100644 --- a/packages/forms/src/UIForm/fieldsets/Array/Array.component.js +++ b/packages/forms/src/UIForm/fieldsets/Array/Array.component.js @@ -36,12 +36,16 @@ export default class ArrayWidget extends Component { onAdd(event) { const arrayMergedSchema = this.props.schema; const { items, schema } = arrayMergedSchema; - const getDefaultValue = schema.items.type === 'object' ? {} : ''; const hasOneItem = items.length === 1; const itemsEnum = get(schema, 'items.enum'); const isSingleSelectItem = hasOneItem && head(items).type === 'select' && head(itemsEnum); - const defaultValue = isSingleSelectItem ? head(itemsEnum) : getDefaultValue; + const schemaDefaultConfig = schema.default?.[0]; + const defaultConfig = schema.items.type === 'object' ? {} : ''; + + const defaultValue = isSingleSelectItem + ? head(itemsEnum) + : schemaDefaultConfig || defaultConfig; let currentValue = this.props.value; if (this.isCloseable()) { diff --git a/packages/forms/src/UIForm/fieldsets/Array/Array.component.test.js b/packages/forms/src/UIForm/fieldsets/Array/Array.component.test.js index c8fba2d8aa3..0d51ce978d3 100644 --- a/packages/forms/src/UIForm/fieldsets/Array/Array.component.test.js +++ b/packages/forms/src/UIForm/fieldsets/Array/Array.component.test.js @@ -243,6 +243,40 @@ describe('Array component', () => { expect(props.onChange).toHaveBeenCalledWith(expect.anything(), payload); expect(props.onFinish).toHaveBeenCalledWith(expect.anything(), payload); }); + + it('should add default value from schema as default value for new item', async () => { + const defaultValue = { + name: 'default name', + email: 'default email', + comment: 'default comment', + }; + + const enhancedSchema = { + ...schema, + schema: { + ...schema.schema, + default: [defaultValue], + }, + }; + + // given + render( + + + , + ); + + // when + await userEvent.click(screen.getByText('Add')); + + // then + const payload = { + schema: enhancedSchema, + value: [defaultValue], + }; + expect(props.onChange).toHaveBeenCalledWith(expect.anything(), payload); + expect(props.onFinish).toHaveBeenCalledWith(expect.anything(), payload); + }); }); describe('#onRemove', () => {