blob: 6713fe73857a9caadc507cc76847e839ab1fae3e [file] [log] [blame]
Matteo Scandoloee655a12016-12-19 15:38:43 -08001// TODO clean this mess
2
3import * as _ from 'lodash';
4import {IXosFormHelpersService} from './form-helpers';
5import {IXosConfigHelpersService} from '../services/helpers/config.helpers';
6
Matteo Scandolo80c3a652017-01-06 10:48:31 -08007export interface IXosFormAction {
8 label: string;
9 icon: string;
10 class: string;
11 cb(item: any, form: any): void;
12}
13
14export interface IXosFeedback {
15 show: boolean;
16 message: string;
17 type: string; // NOTE is possible to enumerate success, error, warning, info?
18}
19
20export interface IXosFormInputValidator {
21 minlength?: number;
22 maxlength?: number;
23 required?: boolean;
24 min?: number;
25 max?: number;
26 custom?(value: any): any;
27 // do your validation here and return true | false
28 // alternatively you can return an array [errorName, true|false]
29}
30
31export interface IXosFormInput {
32 name: string;
33 label: string;
34 type: string; // options are: [date, boolean, number, email, string, select],
35 validators: IXosFormInputValidator;
36}
37
38export interface IXosFormConfig {
39 exclude?: string[];
40 actions: IXosFormAction[];
41 feedback?: IXosFeedback;
42 inputs: IXosFormInput[];
43 formName: string;
44}
45
Matteo Scandoloee655a12016-12-19 15:38:43 -080046class FormCtrl {
47 $inject = ['$onInit', '$scope', 'XosFormHelpers', 'ConfigHelpers'];
48
49 public ngModel: any;
50 public excludedField: string[];
51 public formField: any;
52 private config: any;
53
54 constructor (
55 private $scope: ng.IScope,
56 private XosFormHelpers: IXosFormHelpersService,
57 private ConfigHelpers: IXosConfigHelpersService
58 ) {
Matteo Scandoloee655a12016-12-19 15:38:43 -080059 }
60
61 $onInit() {
62 if (!this.config) {
63 throw new Error('[xosForm] Please provide a configuration via the "config" attribute');
64 }
65
66 if (!this.config.actions) {
67 throw new Error('[xosForm] Please provide an action list in the configuration');
68 }
69
Matteo Scandolo80c3a652017-01-06 10:48:31 -080070 if (!this.config.formName) {
71 throw new Error('[xosForm] Please provide a formName property in the config');
72 }
73
74 // NOTE is needed ??
Matteo Scandoloee655a12016-12-19 15:38:43 -080075 if (!this.config.feedback) {
76 this.config.feedback = {
77 show: false,
78 message: 'Form submitted successfully !!!',
79 type: 'success'
80 };
81 }
82
Matteo Scandolo80c3a652017-01-06 10:48:31 -080083 // remove excluded inputs
84 _.remove(this.config.inputs, i => this.config.exclude.indexOf(i.name) > -1);
Matteo Scandoloee655a12016-12-19 15:38:43 -080085 }
86}
87
88export const xosForm: angular.IComponentOptions = {
89 template: require('./form.html'),
90 controllerAs: 'vm',
91 controller: FormCtrl,
92 bindings: {
93 ngModel: '=',
94 config: '='
95 }
96};