1 | <?php |
||
34 | class Form { |
||
35 | /** |
||
36 | * @var Field[] Form Fields |
||
37 | */ |
||
38 | protected $_fields; |
||
39 | protected $_name; |
||
40 | public $hint; |
||
41 | protected $_data; |
||
42 | /** |
||
43 | * Setup Method |
||
44 | * Fills the $this->fields array with hamleFields |
||
45 | */ |
||
46 | function setup() { |
||
47 | throw new Exception\RunTime("You must configure the form in the setup ". |
||
48 | "function, by adding fields to the \$this->fields array"); |
||
49 | } |
||
50 | |||
51 | function __construct() { |
||
52 | $this->_data = func_get_args(); |
||
53 | $this->_name = get_called_class(); |
||
54 | $this->setup(); |
||
55 | $fields = $this->_fields; |
||
56 | $this->_fields = array(); |
||
57 | foreach($fields as $v) { |
||
58 | $this->_fields[$v->name] = $v; |
||
59 | $v->form($this->_name); |
||
60 | } |
||
61 | $this->postInit(); |
||
62 | } |
||
63 | function postInit() {} |
||
64 | |||
65 | function process() { |
||
66 | $clicked = ""; |
||
67 | foreach($this->_fields as $f) |
||
68 | if($f instanceOf Field\Button) |
||
69 | if($f->isClicked()) |
||
70 | $clicked = $f; |
||
71 | foreach($this->_fields as $f) |
||
72 | $f->doProcess($clicked?true:false); |
||
73 | if($clicked) |
||
74 | try { |
||
75 | $this->onSubmit($clicked); |
||
76 | } catch(Exception\FormInvalid $e) { |
||
77 | $this->hint = $e->getMessage(); |
||
78 | } |
||
79 | } |
||
80 | |||
81 | function isValid() { |
||
82 | $valid = true; |
||
83 | foreach($this->_fields as $f) |
||
84 | $valid = $f->valid && $valid; |
||
85 | return $valid; |
||
86 | } |
||
87 | /** |
||
88 | * Called upon form submission, $button will be assigned to the button that was clicked |
||
89 | * @param Field\Button $button |
||
90 | * @throws Exception\NoKey |
||
91 | */ |
||
92 | function onSubmit($button) { } |
||
93 | |||
94 | function getFields() { |
||
95 | return $this->_fields; |
||
96 | } |
||
97 | function getField($n) { |
||
98 | if(!isset($this->_fields[$n])) |
||
99 | throw new Exception\NoKey("unable to find form field ($n)"); |
||
100 | return $this->_fields[$n]; |
||
101 | } |
||
102 | function __get($n) { |
||
103 | return $this->getField($n); |
||
104 | } |
||
105 | |||
106 | function getHTMLProp() { |
||
107 | return array('action'=>'','method'=>'post','name'=>$this->_name, |
||
108 | 'enctype'=>'multipart/form-data'); |
||
109 | } |
||
110 | |||
111 | function preEndTag() { |
||
112 | echo "<input type='hidden' name='{$this->_name}__submit' value='submit' />"; |
||
113 | } |
||
114 | |||
115 | } |
||
116 |