|
23 | 23 |
|
24 | 24 | let isValid; |
25 | 25 | let form; |
26 | | - let fieldPaths; |
| 26 | + let fields; |
27 | 27 |
|
28 | 28 | onMount(() => { |
29 | | - fieldPaths = new Set( |
30 | | - Array.from(form.querySelectorAll('input,textarea,select')) |
31 | | - .map(el => el.name) |
32 | | - .filter(name => !!name) |
33 | | - ); |
34 | | - fieldPaths.forEach(registerField); |
35 | | - }); |
| 29 | + fields = Array.from(form.querySelectorAll('input,textarea,select')) |
| 30 | + .filter(el => !!el.name) |
| 31 | + .map(el => ({ path: el.name })) |
| 32 | + .reduce((allElements, currentElement) => { |
| 33 | + const isCurrentElement = el => el.path === currentElement.path; |
| 34 | + const multiple = !!allElements.find(isCurrentElement); |
36 | 35 |
|
37 | | - function registerField(path) { |
38 | | - $values = set($values, path, get(initialValues, path, '')); |
39 | | - $touched = set($touched, path, false); |
40 | | - } |
| 36 | + return [ |
| 37 | + ...allElements.filter(el => !isCurrentElement(el)), |
| 38 | + { ...currentElement, multiple }, |
| 39 | + ]; |
| 40 | + }, []); |
| 41 | +
|
| 42 | + resetForm(); |
| 43 | + }); |
41 | 44 |
|
42 | 45 | setContext(FORM, { |
43 | 46 | touchField, |
|
52 | 55 | }); |
53 | 56 |
|
54 | 57 | function resetForm(data) { |
55 | | - fieldPaths.forEach(path => { |
56 | | - $values = set($values, path, get(data ? data : initialValues, path, '')); |
| 58 | + fields.forEach(({ path, multiple }) => { |
| 59 | + $values = set( |
| 60 | + $values, |
| 61 | + path, |
| 62 | + get(data ? data : initialValues, path, multiple ? [] : '') |
| 63 | + ); |
57 | 64 | $touched = set($touched, path, false); |
58 | 65 | }); |
59 | 66 | $errors = {}; |
60 | 67 | $validatedValues = {}; |
| 68 | + isValid = undefined; |
61 | 69 | } |
62 | 70 |
|
63 | 71 | async function validate() { |
|
95 | 103 | } |
96 | 104 |
|
97 | 105 | async function handleSubmit() { |
98 | | - fieldPaths.forEach(name => ($touched = set($touched, name, true))); |
| 106 | + fields.forEach(({ path }) => ($touched = set($touched, path, true))); |
99 | 107 | await validate(); |
100 | 108 | if (!schema || isValid) { |
101 | 109 | $isSubmitting = true; |
|
0 commit comments