Skip to content

Commit

Permalink
fix(): default value when add item in array widget
Browse files Browse the repository at this point in the history
  • Loading branch information
jmainguytalend committed Jun 28, 2024
1 parent 6ae3477 commit 7c9f9bd
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 7c9f9bd

Please sign in to comment.