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

302 lines
9.1 KiB
TypeScript
Raw Normal View History

import { Component, Input, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { NgForm } from '@angular/forms';
2017-10-30 15:56:50 +01:00
import { Router, ActivatedRoute, ParamMap, Params } 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';
2017-10-09 15:36:29 +02:00
import { PaginationService } from '../../app/services/pagination.service';
2017-10-17 13:58:07 +02:00
import { TokenService, TokenProvider } from '../services/token.service';
import { AngularDraggableModule } from 'angular2-draggable';
2017-10-17 11:13:10 +02:00
import './../../assets/xml2json.min.js';
declare var X2JS: any;
var flatten = require('flat');
import * as $ from '../../../node_modules/jquery/dist/jquery'
import * as scroll from '../../assets/jquery.scrollTo.min.js';
@Component({
selector: 'dynamic-form',
templateUrl: './dynamic-form.component.html',
2017-09-21 12:37:19 +02:00
providers: [FieldControlService, ServerService, dataModelBuilder]
})
export class DynamicFormComponent implements OnInit {
@Input() dataModel: DataModel = new DataModel();
2017-10-04 11:39:45 +02:00
form: FormGroup;
payLoad = '';
@Input() dirtyValues: number = 0;
2017-10-09 15:36:29 +02:00
// pagination object
@Input() pagination: any = {};
2017-10-30 15:56:50 +01:00
id:string;
2017-10-30 16:35:11 +01:00
datasetId:string;
//datasetProperties:string;
2017-10-30 16:35:11 +01:00
private fragment: string;
2017-10-17 11:13:10 +02:00
xml2jsonOBJ: any;
2017-10-09 15:36:29 +02:00
constructor(private qcs: FieldControlService, private serverService: ServerService, private dataModelService: dataModelBuilder, private router: Router,
2017-10-17 13:58:07 +02:00
private route: ActivatedRoute, private pagerService: PaginationService, private tokenService : TokenService) {
2017-09-21 12:32:58 +02:00
this.form = this.qcs.toFormGroup(new Array(), new Array());
2017-10-17 11:13:10 +02:00
this.xml2jsonOBJ = new X2JS();
}
2017-10-04 11:39:45 +02:00
getSubForm(subformName) {
2017-09-29 18:16:37 +02:00
return this.form.controls[subformName];
}
2017-10-04 11:39:45 +02:00
ngOnInit() {
2017-09-26 17:16:04 +02:00
this.route.fragment.subscribe(fragment => { this.fragment = fragment; }); //navigate to certain section of the page
2017-10-04 11:39:45 +02:00
2017-10-30 15:56:50 +01:00
//let id = this.route.snapshot.paramMap.get('id'); //get the project id
2017-10-04 11:39:45 +02:00
2017-10-30 17:37:17 +01:00
let sub = this.route.params.subscribe(params => {
2017-10-30 15:56:50 +01:00
this.id = params.id;
2017-10-30 16:35:11 +01:00
this.datasetId = params.datasetId;
//this.datasetProperties = params.datasetProperties
2017-10-30 15:56:50 +01:00
});
this.serverService.getDatasetProfileByID(this.id).subscribe(
2017-10-18 10:29:22 +02:00
2017-10-17 11:13:10 +02:00
response => {
2017-10-04 11:39:45 +02:00
2017-10-17 11:13:10 +02:00
console.log("response");
console.log(response);
const data = response;
//replace the xmls {model,view,rule} definitions with json -- https://github.com/abdmob/x2js library
2017-10-30 15:56:50 +01:00
data.definition = this.xml2jsonOBJ.xml_str2json(data.definition);
data.ruleset.definition = this.xml2jsonOBJ.xml_str2json(data.ruleset.definition);
data.viewstyle.definition = this.xml2jsonOBJ.xml_str2json(data.viewstyle.definition);
2017-10-17 11:13:10 +02:00
//can be converted back to xml (which shouldn't be needed) with this.xml2jsonOBJ.json2xml_str
console.log("this.serverService.getFields");
2017-10-18 10:29:22 +02:00
console.log("data.dataset")
2017-10-30 15:56:50 +01:00
console.log(data.definition)
console.log(data.ruleset.definition)
console.log(data.viewstyle.definition)
2017-10-18 10:29:22 +02:00
2017-10-17 11:13:10 +02:00
this.dataModel = new DataModel();
this.dataModel = this.dataModelService.getDataModel(data);
2017-10-04 11:39:45 +02:00
2017-09-21 12:32:58 +02:00
this.form = this.qcs.toFormGroup(this.dataModel.fields, this.dataModel.groups);
2017-10-04 11:39:45 +02:00
2017-10-03 17:36:09 +02:00
this.form.valueChanges.subscribe(data => {
2017-10-09 15:36:29 +02:00
// console.log('Form changes', data);
2017-10-03 17:36:09 +02:00
let dirtyValuesArray: Array<any> = [];
let count = 0;
2017-10-04 11:39:45 +02:00
let countDirtyValues = 0;
2017-10-09 15:36:29 +02:00
Object.keys(this.form.controls).forEach((c) => {
2017-10-04 11:39:45 +02:00
//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++;
2017-10-17 12:16:48 +02:00
if (fld.value != undefined && fld.value !=" ")
2017-10-04 11:39:45 +02:00
countDirtyValues++;
});
});
//console.log(count);
2017-10-09 15:36:29 +02:00
// var percentage = Math.floor(dirtyValuesArray.length * 100 / count);
2017-10-04 11:39:45 +02:00
var percentage = Math.floor(countDirtyValues * 100 / count);
this.dirtyValues = percentage;
2017-10-03 17:36:09 +02:00
})
2017-10-04 11:39:45 +02:00
//this.form = this.qcs.toFormGroup(this.fields);
2017-10-04 11:39:45 +02:00
console.log("SUMMARY: ======>");
console.log(this.dataModel);
console.log(this.form);
this.route.paramMap //this is how i get the projects's id
2017-10-09 15:36:29 +02:00
// initialize to page 1
this.setPage(1);
2017-10-17 11:13:10 +02:00
},
2017-10-17 11:13:10 +02:00
err => {
console.log("There was an error fetching the data from server");
console.log(err);
}
);
2017-10-04 11:39:45 +02:00
this.serverService.getDatasetByID(this.datasetId).subscribe(
(data) => {
if(data.properties){
console.log("Found already submitted form, loading that one!");
//console.log(data.properties)
//console.log(JSON.parse(data.properties))
let formValues = JSON.parse(data.properties);
var flatList = flatten(formValues);
this.patchForm(flatList);
}
},
(err) => {
});
}
scrollToElemID(elemID){
scroll("#"+elemID);
}
private patchForm(flatList : any){
for (var prop in flatList) {
if (flatList.hasOwnProperty(prop)) {
if(prop.endsWith('.id')||prop.endsWith('.answer')||prop.endsWith('.value')) continue;
//console.log("updating value of "+prop +" to "+flatList[prop].valueOf())
this.form.get(prop).setValue(flatList[prop].valueOf());
}
}
//this.form.get("namingConventionGroup.nonamingConventionA213").setValue("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
}
ngAfterViewChecked(): void { //navigate to certain section of the page
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}
onSubmit() {
this.serverService.getDatasetByID(this.datasetId).subscribe(
(data) => {
//is xml, so transform them to xml (it's json)
//data.properties = this.xml2jsonOBJ.json2xml_str(JSON.stringify(this.form.value));
data.properties = JSON.stringify(this.form.value);
this.serverService.setDataset(data).subscribe( (data) => {
console.log("Updated dataset");
//VALE EDW NA SE PIGAINEI PISW KAI NA SOU VGAZEI ENA MHNYMA SUCCESS... (to success tha to valw egw an thes)
},
(err) => {
});
},
(err) => {
});
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
}
2017-10-09 15:36:29 +02:00
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);
}
signOut2() {
2017-10-17 12:16:48 +02:00
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
2017-10-17 13:58:07 +02:00
localStorage.removeItem('currentUser');
2017-10-17 12:16:48 +02:00
    });
2017-10-17 13:58:07 +02:00
this.tokenService.setToken(null); //kanonika prepei na mpei mesa sthn function.....
2017-10-17 12:16:48 +02:00
  }
onValueChanged(data?: any) {
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.'
}
};
}