|
@@ -1,15 +1,42 @@
|
|
|
import { FormBuilder, FormControl } from '@angular/forms';
|
|
|
-import { map, reduce } from 'lodash/fp';
|
|
|
+import { reduce } from 'lodash/fp';
|
|
|
+
|
|
|
+
|
|
|
+ * FORM UTILITIES
|
|
|
+ *
|
|
|
+ * Exports
|
|
|
+ * -------
|
|
|
+ * buildFormGroup(metadata) - builds FormGroups from metdata, recursively if necessary
|
|
|
+ * addMissingNames(metadata) - adds any missing 'name' properties to Fields and Groups using property's key, recursively
|
|
|
+ *
|
|
|
+ * Variable names
|
|
|
+ * --------------
|
|
|
+ * metaF = metadata for Field
|
|
|
+ * metaG = metadata for Group (possibly nested)
|
|
|
+ * metaFoG = metadata for Field Or Group
|
|
|
+ *
|
|
|
+ */
|
|
|
|
|
|
const fb = new FormBuilder();
|
|
|
|
|
|
-
|
|
|
-const addNameIfMissing = (val, key) => val.name ? val : Object.assign(val, { name: key });
|
|
|
-
|
|
|
+
|
|
|
+const isGroup = metaFoG => metaFoG.meta && !metaFoG._field;
|
|
|
|
|
|
+
|
|
|
+const addNameIfMissing = (metaFoG, key) => metaFoG.name ? metaFoG : Object.assign(metaFoG, { name: key });
|
|
|
+const addNameToSelfAndChildren = ( [key, metaFoG] ) => {
|
|
|
+ metaFoG = addNameIfMissing(metaFoG, key);
|
|
|
+ if (isGroup(metaFoG)) {
|
|
|
+ metaFoG = addMissingNames(metaFoG.meta);
|
|
|
+ }
|
|
|
+ return [key, metaFoG];
|
|
|
+};
|
|
|
+const addMissingNames = metaG => Object.entries(metaG)
|
|
|
+ .map(addNameToSelfAndChildren)
|
|
|
+ .reduce((res, [key, val]) => { res[key] = val; return res; }, {});
|
|
|
|
|
|
|
|
|
-
|
|
|
+
|
|
|
const buildControlState = metaF => ({ value: metaF.value || '', disabled: metaF.isDisabled });
|
|
|
const buildValidators = metaF => ({
|
|
|
validators: null,
|
|
@@ -19,19 +46,13 @@ const buildValidators = metaF => ({
|
|
|
const buildFormControl = metaF => new FormControl(buildControlState(metaF) );
|
|
|
|
|
|
|
|
|
-
|
|
|
-const isGroup = metaFoG => metaFoG.meta && !metaFoG._field;
|
|
|
const buildFormGroupMember = metaFoG => isGroup(metaFoG) ? buildFormGroup(metaFoG.meta) : buildFormControl(metaFoG);
|
|
|
|
|
|
-
|
|
|
+
|
|
|
const buildFormGroupReducerIteree = (res, metaFoG) => Object.assign(res, { [metaFoG.name]: buildFormGroupMember(metaFoG) });
|
|
|
const buildFormGroup = metaG => fb.group(reduce(buildFormGroupReducerIteree, {}, metaG));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-export { buildFormGroup };
|
|
|
-
|
|
|
-
|
|
|
-
|
|
|
-
|
|
|
+export { addMissingNames, buildFormGroup };
|