Skip to content

Commit 77beab5

Browse files
Georgi2704Georgi2704
andauthored
Display always items in ArrayField depending on the minItems (#194)
Co-authored-by: Georgi2704 <georgi.manev@surf.nl>
1 parent b431959 commit 77beab5

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

frontend/packages/pydantic-forms/src/components/fields/ArrayField.tsx

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import React, { useCallback, useEffect } from 'react';
22
import { useFieldArray } from 'react-hook-form';
33

44
import { useGetConfig, useGetForm } from '@/core';
@@ -21,6 +21,19 @@ export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
2121
const { minItems = 1, maxItems = undefined } =
2222
pydanticFormField?.validations;
2323

24+
const appendDefault = useCallback(() => {
25+
append({
26+
[arrayName]: arrayItem?.default ?? undefined,
27+
});
28+
}, [append, arrayItem?.default, arrayName]);
29+
30+
useEffect(() => {
31+
if (arrayName && arrayItem && minItems && fields) {
32+
const missingCount = Math.max(0, minItems - fields.length);
33+
Array.from({ length: missingCount }).forEach(() => appendDefault());
34+
}
35+
}, [minItems, append, remove, arrayItem, arrayName, fields, appendDefault]);
36+
2437
if (!arrayItem) return '';
2538

2639
const component = fieldToComponentMatcher(
@@ -85,11 +98,7 @@ export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
8598
{(!maxItems || (maxItems && fields.length < maxItems)) &&
8699
!disabled && (
87100
<div
88-
onClick={() => {
89-
append({
90-
[arrayName]: arrayItem.default,
91-
});
92-
}}
101+
onClick={appendDefault}
93102
style={{
94103
cursor: 'pointer',
95104
fontSize: '32px',

0 commit comments

Comments
 (0)