Skip to content

Commit

Permalink
feat: prevent form appear if no type-site
Browse files Browse the repository at this point in the history
- Hide form if btn-list type-site not selected
- Add custom error message mat-error if not selected (directive + custom
  message)

WIP: error message is showing up only if not selected after touched .
Maybe need to use asyncValidator ?

Reviewed-by: andriac
[Refs_tickets]: #5 , #6 , #54
  • Loading branch information
andriacap committed Apr 19, 2023
1 parent 77d1c56 commit 27d05e6
Show file tree
Hide file tree
Showing 11 changed files with 105 additions and 13 deletions.
3 changes: 2 additions & 1 deletion frontend/app/components/btn-select/btn-select.component.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<mat-form-field class="example-chip-list" appearance="fill">
<mat-label>{{ titleBtn }}</mat-label>
<mat-chip-list #chipList aria-label="option selection">
<mat-chip-list #chipList aria-label="option selection" [formControl]="listOpNeeded">
<mat-chip
*ngFor="let optionSelected of listOptionChosen"
[selectable]="selectable"
Expand Down Expand Up @@ -28,4 +28,5 @@
</mat-option>
</ng-container>
</mat-autocomplete>
<mat-error matErrorMessages></mat-error>
</mat-form-field>
13 changes: 11 additions & 2 deletions frontend/app/components/btn-select/btn-select.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import {
Output,
ViewChild,
} from '@angular/core';
import { FormControl } from '@angular/forms';
import { FormControl, Validators } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { Observable, iif, of } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators';

import { JsonData } from '../../types/jsondata';
import { FormService } from '../../services/form.service';

export interface EmptyObject {
name: string;
Expand All @@ -30,6 +31,7 @@ export class BtnSelectComponent implements OnInit {
isInit = false;
separatorKeysCodes: number[] = [ENTER, COMMA];
myControl = new FormControl();
listOpNeeded = new FormControl([],[Validators.required, Validators.minLength(1)])
@Input() placeholderText: string = 'Selectionnez vos options dans la liste';
@Input() titleBtn: string = 'Choix des options';

Expand All @@ -52,9 +54,10 @@ export class BtnSelectComponent implements OnInit {

@Output() public sendobject = new EventEmitter<JsonData>();

constructor() {}
constructor(private _formService: FormService) { }

ngOnInit() {

if(this.isInitialValues && !this.isInit){
this.initFromExistingObj(this.paramToFilt)
this.objToEdit.map(val => this.addObject(val))
Expand All @@ -73,6 +76,8 @@ export class BtnSelectComponent implements OnInit {
}),
map((res) => (res.length > 0 ? res : [{ name: 'Pas de résultats' }]))
);
this.listOpNeeded.setValue(this.listOptionChosen)
this._formService.changeExtraFormControl(this.listOpNeeded,"listOptBtnSelect")
}

remove(option: string): void {
Expand All @@ -86,6 +91,8 @@ export class BtnSelectComponent implements OnInit {
delete this.configObjAdded[option];
}
this.sendobject.emit(this.configObjAdded);
this.listOpNeeded.setValue(this.listOptionChosen)
this._formService.changeExtraFormControl(this.listOpNeeded,"listOptBtnSelect")
}

selected(event: MatAutocompleteSelectedEvent): void {
Expand All @@ -95,6 +102,8 @@ export class BtnSelectComponent implements OnInit {
: null;
this.optionInput.nativeElement.value = '';
this.myControl.setValue(null);
this.listOpNeeded.setValue(this.listOptionChosen)
this._formService.changeExtraFormControl(this.listOpNeeded,"listOptBtnSelect")
}

filterOnRequest(val: string, keyToFilt: string): Observable<any> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ <h2>Attention</h2>
</pnx-modal-msg>

<div>
<div id="properties-form" class="cadre">
<div id="properties-form" class="cadre" *ngIf="!hideForm">
<!-- TODO: voir pour intiialisation si nécessaire à remettre dans la div du dessus -->
<!-- *ngIf="obj.bIsInitialized && objFormsDefinition" -->

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { IDataForm } from '../../interfaces/form';
import { ApiGeomService } from '../../services/api-geom.service';
import { ConfigJsonService } from '../../services/config-json.service';
import { FormService } from '../../services/form.service';
import { ObjectService } from '../../services/object.service';
import { IExtraForm } from '../../interfaces/object';

@Component({
selector: 'pnx-monitoring-form-g',
Expand All @@ -34,6 +34,10 @@ export class MonitoringFormComponentG implements OnInit {

@Input() sites: {};
@Input() apiService: ApiGeomService;
@Input() isExtraForm:boolean = false;

extraForm: IExtraForm;
hideForm: boolean = false;
dataForm: IDataForm;
searchSite = '';

Expand Down Expand Up @@ -68,11 +72,16 @@ export class MonitoringFormComponentG implements OnInit {
tap((data) => {
this.obj = data;
this.obj.bIsInitialized = true;
this.apiService.init(this.obj.endPoint, this.obj.objSelected);
this.obj.id = this.obj[this.obj.pk]
}),
mergeMap((data: any) => this._configService.init(data.moduleCode))
mergeMap((data: any) => this._configService.init(data.moduleCode)),
mergeMap(() => this._formService.currentExtraFormCtrl )
)
.subscribe(() => {
.subscribe((frmCtrl) => {

this.isExtraForm ? this.addExtraFormCtrl(frmCtrl) : null;
this.isExtraForm ? this.checkValidExtraFormCtrl() : null;


this.queryParams = this._route.snapshot.queryParams || {};
this.bChainInput = this._configService.frontendParams()['bChainInput'];
Expand Down Expand Up @@ -293,7 +302,6 @@ export class MonitoringFormComponentG implements OnInit {
onSubmit() {
const { patch_update, ...sendValue } = this.dataForm;
const objToUpdateOrCreate = this._formService.postData(sendValue, this.obj);
console.log(objToUpdateOrCreate);
const action = this.obj.id
? this.apiService.patch(this.obj.id, objToUpdateOrCreate)
: this.apiService.create(objToUpdateOrCreate);
Expand Down Expand Up @@ -381,6 +389,25 @@ export class MonitoringFormComponentG implements OnInit {
this.procesPatchUpdateForm();
}

addExtraFormCtrl(frmCtrl: IExtraForm){
if (frmCtrl.frmName in this.objForm.controls){
this.objForm.setControl(frmCtrl.frmName,frmCtrl.frmCtrl)
} else{
this.objForm.addControl(frmCtrl.frmName,frmCtrl.frmCtrl)
}

this.extraForm = frmCtrl
}

checkValidExtraFormCtrl(){
if (this.extraForm.frmName in this.objForm.controls && this.objForm.get(this.extraForm.frmName).value != null && this.objForm.get(this.extraForm.frmName).value.length != 0 ){
this.hideForm = false
this.objForm.valid
} else {
this.hideForm = true
}
}

getConfigFromBtnSelect(event) {
// this.obj.specific == undefined ? (this.obj.specific = {}) : null;
// TODO: Ajout de tous les id_parents ["id_sites_groups" etc ] dans l'objet obj.dataComplement
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<div>
<pnx-monitoring-form-g
[apiService]="siteService"
[isExtraForm]="true"
[objForm]="form"
#subscritionObjConfig
></pnx-monitoring-form-g>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*ngIf="bEdit"
[(bEdit)]="bEdit"
[apiService]="siteService"
[isExtraForm]="true"
></pnx-monitoring-form-g>
<pnx-monitoring-properties-g
*ngIf="!bEdit"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export class MonitoringVisitsComponent extends MonitoringGeomComponent implement
.subscribe((data: { site: ISite; visits: IPaginated<IVisit> }) => {
this._objService.changeSelectedObj(data.site, true);
this.site = data.site;
this.types_site = data.site['types_site']
this.setVisits(data.visits);
this.baseFilters = { id_base_site: this.site.id_base_site };
});
Expand Down Expand Up @@ -163,7 +164,8 @@ export class MonitoringVisitsComponent extends MonitoringGeomComponent implement
}

initValueToSend(){
return this.site['types_site']
this.initSiteVisit()
return this.types_site
}

updateForm(){
Expand Down
3 changes: 2 additions & 1 deletion frontend/app/gnModule.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import { BtnSelectComponent } from "./components/btn-select/btn-select.component
import { MonitoringSitesEditComponent } from "./components/monitoring-sites-edit/monitoring-sites-edit.component";
import { MonitoringVisitsComponent } from "./components/monitoring-visits/monitoring-visits.component";
import { OptionListButtonComponent } from "./components/option-list-btn/option-list-btn.component";

import { MatErrorMessagesDirective } from './utils/matErrorMessages.directive';
// my module routing
const routes: Routes = [
/** modules */
Expand Down Expand Up @@ -137,6 +137,7 @@ const routes: Routes = [
BtnSelectComponent,
MonitoringVisitsComponent,
OptionListButtonComponent,
MatErrorMessagesDirective
],
imports: [
GN2CommonModule,
Expand Down
3 changes: 3 additions & 0 deletions frontend/app/interfaces/object.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AbstractControl } from "@angular/forms";
import { JsonData } from "../types/jsondata";
import { IPaginated } from "./page";
import { GeoJSON } from "geojson";
Expand All @@ -23,3 +24,5 @@ export type SelectObject = {
label: string;
};


export type IExtraForm = {frmCtrl :AbstractControl,frmName:string}
14 changes: 12 additions & 2 deletions frontend/app/services/form.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,29 @@ import { BehaviorSubject, Observable, forkJoin, of } from 'rxjs';
import { concatMap } from 'rxjs/operators';

import { ISite, ISitesGroup } from '../interfaces/geom';
import { IobjObs, ObjDataType } from '../interfaces/objObs';
import { JsonData } from '../types/jsondata';
import { Utils } from '../utils/utils';
import { MonitoringObjectService } from './monitoring-object.service';
import { FormControl } from '@angular/forms';
import { IExtraForm } from '../interfaces/object';


@Injectable()
export class FormService {
data: JsonData = {};
frmCtrl: FormControl = new FormControl(null);
frmCtrlName: string = '';
private dataSub = new BehaviorSubject<object>(this.data);
private formCtrl = new BehaviorSubject<IExtraForm>({frmCtrl : this.frmCtrl,frmName:this.frmCtrlName});
currentData = this.dataSub.asObservable();
currentExtraFormCtrl = this.formCtrl.asObservable();
properties: JsonData = {};
moduleCode: string;
objecType: string;

constructor(private _objService: MonitoringObjectService) {}

// TODO: voir si nécessaire de garder ça (objService permet d'avoir le bon objet ? et sinon modifier pour obtenir ce qu'il faut en formulaire)

changeDataSub(
newDat: JsonData,
objectType: string,
Expand All @@ -40,6 +46,10 @@ export class FormService {
this.dataSub.next(newDat);
}

changeExtraFormControl(formCtrl:FormControl,formCtrlName:string){
this.formCtrl.next({frmCtrl:formCtrl,frmName:formCtrlName})
}

formValues(obj): Observable<any> {
// const {properties ,remainaing} = obj
const properties = Utils.copy(this.properties);
Expand Down
37 changes: 37 additions & 0 deletions frontend/app/utils/matErrorMessages.directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Component, AfterViewInit, Injector } from '@angular/core';
import {MatInput } from '@angular/material/input';
import { MatFormFieldControl,MatFormField } from '@angular/material/form-field';

@Component({
selector: '[matErrorMessages]',
template: '{{ error }}'
})
export class MatErrorMessagesDirective implements AfterViewInit {
error = '';
inputRef: MatFormFieldControl<MatInput>;

constructor(private _inj: Injector) { }

// Setup all initial tooling
ngAfterViewInit() {
// grab reference to MatFormField directive, where form control is accessible.
let container = this._inj.get(MatFormField);
this.inputRef = container._control;

// sub to the control's status stream
this.inputRef.ngControl.statusChanges.subscribe(this.updateErrors);
}

// This grabs a single active error instead of multiple.
private updateErrors = (state: 'VALID' | 'INVALID') => {
if (state === 'INVALID') {
let controlErrors = this.inputRef.ngControl.errors;
const firstError = Object.keys(controlErrors)[0];
if(firstError === 'required')
this.error = 'Ce champs est requis.';

if(firstError === 'minlength')
this.error = 'Vous devez choisir au moins une valeur.';
}
}
}

0 comments on commit 27d05e6

Please sign in to comment.