Skip to content

Commit

Permalink
fix(): default value when add item in array widget (#5364)
Browse files Browse the repository at this point in the history
Co-authored-by: jmainguytalend <[email protected]>
  • Loading branch information
jmainguytalend and jmainguytalend authored Jul 8, 2024
1 parent 101e6c4 commit 194465c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/itchy-stingrays-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@talend/react-forms": patch
---

Forms: array widget - use default value when add new item
8 changes: 6 additions & 2 deletions packages/forms/src/UIForm/fieldsets/Array/Array.component.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
34 changes: 34 additions & 0 deletions packages/forms/src/UIForm/fieldsets/Array/Array.component.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<WidgetContext.Provider value={defaultWidgets}>
<ArrayWidget {...props} schema={enhancedSchema} value={[]} />
</WidgetContext.Provider>,
);

// 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', () => {
Expand Down

0 comments on commit 194465c

Please sign in to comment.