From 5a98659ae707b0db0213ffc2d685606d730e1e1a Mon Sep 17 00:00:00 2001 From: Etienne Delclaux Date: Fri, 2 Feb 2024 17:33:25 +0100 Subject: [PATCH] feat: fieldmapping synchro --- .../fields-mapping-step.component.ts | 46 ++++++++++++------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/frontend/src/app/modules/imports/components/import_process/fields-mapping-step/fields-mapping-step.component.ts b/frontend/src/app/modules/imports/components/import_process/fields-mapping-step/fields-mapping-step.component.ts index 5386e92260..bbd967303e 100644 --- a/frontend/src/app/modules/imports/components/import_process/fields-mapping-step/fields-mapping-step.component.ts +++ b/frontend/src/app/modules/imports/components/import_process/fields-mapping-step/fields-mapping-step.component.ts @@ -136,26 +136,38 @@ export class FieldsMappingStepComponent implements OnInit { !this.syntheseForm.get(field.name_field).value ); } + + // add fields to the form + // when a field is referred multiple times, the same control is used with multiple observers populateSyntheseForm() { - let validators: Array; - // TODO: use the same form control for fields shared between two entities - for (let entity of this.targetFields) { - for (let theme of entity.themes) { - for (let field of theme.fields) { - if (!field.autogenerated) { - // autogenerated = checkbox - this.unmappedTargetFields.add(field.name_field); - } - if (field.mandatory) { - validators = [Validators.required]; + for (const entity of this.targetFields) { + for (const theme of entity.themes) { + for (const field of theme.fields) { + const key = field.name_field; + if (!(key in this.syntheseForm.controls)) { + // A new control + if (!field.autogenerated) { + // autogenerated = checkbox + this.unmappedTargetFields.add(key); + } + const validators: Array = field.mandatory ? [Validators.required] : []; + const control = new FormControl(null, validators); + control.valueChanges.subscribe((value) => { + this.onFieldMappingChange(key, value); + }); + this.syntheseForm.addControl(key, control); } else { - validators = []; + // If a control with a given name already exists, it would not be replaced with a new one. + // The existing one will be updated with a new obser. We make sure to sync the references of it. + this.syntheseForm.controls[key].valueChanges.subscribe((value) => { + this.syntheseForm.controls[key].setValue(value, { + onlySelf: true, + emitEvent: false, + emitModelToViewChange: true, + }); + }); + this.syntheseForm.addControl(key, this.syntheseForm.controls[key]); } - let control = new FormControl(null, validators); - control.valueChanges.subscribe((value) => { - this.onFieldMappingChange(field.name_field, value); - }); - this.syntheseForm.addControl(field.name_field, control); } } }