-
Notifications
You must be signed in to change notification settings - Fork 43
/
useForm.js
76 lines (67 loc) · 1.72 KB
/
useForm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import {ref} from 'vue';
function getField(form, name) {
const fields = form.fields;
return fields.find((field) => field.name === name);
}
function getClearValue(field, localeKey = null) {
if (localeKey) {
if (field.component === 'field-slider') {
return field.min;
}
return Array.isArray(field.value[localeKey]) || field.selected ? [] : '';
}
if (field.component === 'field-slider') {
return field.min;
}
return Array.isArray(field.value) || field.selected ? [] : '';
}
function mapFromSelectedToValue(selected) {
return selected.map((iv) => iv.value);
}
export function useForm(_form) {
const form = ref(_form);
function setValue(name, inputValue) {
const field = getField(form.value, name);
if (!field) {
return;
}
if (field.selected) {
if (field.isMultilingual) {
field.value = {};
Object.keys(inputValue).forEach((localeKey) => {
field.value[localeKey] = mapFromSelectedToValue(
inputValue[localeKey],
);
});
field.selected = inputValue;
} else {
const onlyValues = mapFromSelectedToValue(inputValue);
field.value = onlyValues;
field.selected = inputValue;
}
} else {
field.value = inputValue;
}
}
function clearForm() {
form.value.fields.forEach((field) => {
if (field.isMultilingual) {
const newValueMultilingual = {};
form.value.supportedFormLocales.forEach((localeObject) => {
const localeKey = localeObject.key;
const newValue = getClearValue(field, localeKey);
newValueMultilingual[localeKey] = newValue;
});
setValue(field.name, newValueMultilingual);
} else {
const newValue = getClearValue(field);
setValue(field.name, newValue);
}
});
}
return {
setValue,
clearForm,
form,
};
}