1 /**
2  * Skadi.d Web Framework
3  * Form Component
4 
5  * Authors: Faianca
6  * Copyright: Copyright (c) 2015 Faianca
7  * License: MIT License, see LICENSE
8  */
9 module skadi.components.form.form;
10 
11 import skadi.components.form.elementInterface;
12 import skadi.components.validation.all;
13 
14 
15 
16 class Form
17 {
18 
19 protected:
20     MessageList _messages;
21     ElementInterface[string] _elements;
22 
23 public:
24 
25 
26     /**
27 	 * Adds an element to the form
28 	 */
29 	Form add(ElementInterface element, string postion = null, bool type = false)
30 	{
31 		/**
32 		 * Gets the element's name
33 		 */
34 		string name = element.getName();
35 
36 		/**
37 		 * Link the element to the form
38 		 */
39 		element.setForm(this);
40         this._elements[name] = element;
41 
42 		return this;
43 	}
44 
45     /**
46 	 * Returns the messages generated in the validation
47 	 */
48 	MessageInterface[] getMessages()
49 	{
50 		return this._messages.getMessages();
51 	}
52 
53     /**
54 	 * Renders a specific item in the form
55 	 */
56 	string render(string name)
57 	{
58 		if (name !in this._elements) {
59 			throw new Exception("Element with ID=" ~ name ~ " is not part of the form");
60 		}
61 
62 		return this._elements[name].render();
63 	}
64 
65     /**
66 	 * Validates the form
67 	 *
68 	 * @param array data
69 	 * @param object entity
70 	 * @return boolean
71 	 */
72 	bool isValid(string[string] data)
73 	{
74         import std.stdio;
75         auto validation = new Validation();
76 
77         foreach(field, value; data) {
78             if (field in this._elements) {
79                 ValidatorInterface[] validators = this._elements[field].getValidators();
80                 foreach(ValidatorInterface validator; validators) {
81                     validator.validate(validation, value); // noticeee
82                 }
83             }
84         }
85         this._messages = validation.getMessages();
86 		return this._messages.isEmpty();
87 	}
88 
89 }