argos/dmp-frontend/src/app/form/dynamic-form.component.ts

193 lines
6.4 KiB
TypeScript

import { Component, Input, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import 'rxjs/add/operator/switchMap';
//import { FieldBase } from '../../app/form/fields/field-base';
import { FieldControlService } from '../../app/services/field-control.service';
import { ServerService } from '../../app/services/server.service';
import { dataModelBuilder } from '../../app/services/dataModelBuilder.service';
import { DataModel } from '../entities/DataModel';
import { GroupBase } from './dynamic-form-group/group-base';
import { PaginationService } from '../../app/services/pagination.service';
import './../../assets/xml2json.min.js';
declare var X2JS: any;
@Component({
selector: 'dynamic-form',
templateUrl: './dynamic-form.component.html',
providers: [FieldControlService, ServerService, dataModelBuilder]
})
export class DynamicFormComponent implements OnInit {
@Input() dataModel: DataModel = new DataModel();
form: FormGroup;
payLoad = '';
@Input() dirtyValues: number = 0;
// pagination object
@Input() pagination: any = {};
private fragment: string;
xml2jsonOBJ: any;
constructor(private qcs: FieldControlService, private serverService: ServerService, private dataModelService: dataModelBuilder, private router: Router,
private route: ActivatedRoute, private pagerService: PaginationService) {
this.form = this.qcs.toFormGroup(new Array(), new Array());
this.xml2jsonOBJ = new X2JS();
}
getSubForm(subformName) {
return this.form.controls[subformName];
}
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; }); //navigate to certain section of the page
console.log("DynamicFormComponent.ngOnInit() -- RUNNIGN");
let id = this.route.snapshot.paramMap.get('id'); //get the project id
this.serverService.getData().subscribe(
response => {
console.log("response");
console.log(response);
const data = response;
//replace the xmls {model,view,rule} definitions with json -- https://github.com/abdmob/x2js library
data.dataset.profile.definition = this.xml2jsonOBJ.xml_str2json(data.dataset.profile.definition);
data.dataset.profile.ruleset.definition = this.xml2jsonOBJ.xml_str2json(data.dataset.profile.ruleset.definition);
data.dataset.profile.viewstyle.definition = this.xml2jsonOBJ.xml_str2json(data.dataset.profile.viewstyle.definition);
//can be converted back to xml (which shouldn't be needed) with this.xml2jsonOBJ.json2xml_str
console.log("this.serverService.getFields");
this.dataModel = new DataModel();
this.dataModel = this.dataModelService.getDataModel(data);
this.form = this.qcs.toFormGroup(this.dataModel.fields, this.dataModel.groups);
this.form.valueChanges.subscribe(data => {
// console.log('Form changes', data);
let dirtyValuesArray: Array<any> = [];
let count = 0;
let countDirtyValues = 0;
Object.keys(this.form.controls).forEach((c) => {
//count++;
let currentControl = this.form.controls[c];
if (currentControl.dirty)
dirtyValuesArray.push(currentControl.value);
});
this.dataModel.groups.forEach(grp => {
grp.groupFields.forEach((fld) => {
if (fld.visible == true || fld.visible == "true")
count++;
if (fld.value != undefined)
countDirtyValues++;
});
});
//console.log(count);
// var percentage = Math.floor(dirtyValuesArray.length * 100 / count);
var percentage = Math.floor(countDirtyValues * 100 / count);
this.dirtyValues = percentage;
})
//this.form = this.qcs.toFormGroup(this.fields);
console.log("SUMMARY: ======>");
console.log(this.dataModel);
console.log(this.form);
this.route.paramMap //this is how i get the projects's id
// initialize to page 1
this.setPage(1);
},
err => {
console.log("There was an error fetching the data from server");
console.log(err);
}
);
}
ngAfterViewChecked(): void { //navigate to certain section of the page
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
}
buildForm(): void {
//this.form = this.qcs.toFormGroup(this.fields.
this.form.valueChanges
.subscribe(data => this.onValueChanged(data));
this.onValueChanged(); // (re)set validation messages now
}
setPage(page: number) {
if (page < 1 || page > this.pagination.totalPages) {
return;
}
// get pagination object from service
this.pagination = this.pagerService.getPagination(this.dataModel.groups.length, page);
// get current page of items
this.dataModel.sections.forEach(section => {
if(section.groupFields.length > 0){
section.groupFields = this.dataModel.groups.slice(this.pagination.startIndex, this.pagination.endIndex + 1);
}
});
//this.dataModel.groups = this.dataModel.groups.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
onValueChanged(data?: any) {
debugger;
if (!this.form) { return; }
const form = this.form;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
formErrors = {
'name': '',
'power': ''
};
validationMessages = {
'name': {
'required': 'Name is required.',
'minlength': 'Name must be at least 4 characters long.',
'maxlength': 'Name cannot be more than 24 characters long.',
'forbiddenName': 'Someone named "Bob" cannot be a hero.'
},
'power': {
'required': 'Power is required.'
}
};
}