2ae22002 |
1 | <?php // $Id$ |
da6f8763 |
2 | /** |
3 | * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms. |
da1320da |
4 | * |
5 | * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php |
6 | * and you want to name your class something like {modulename}_{purpose}_form. Your class will |
7 | * extend moodleform overriding abstract classes definition and optionally defintion_after_data |
8 | * and validation. |
9 | * |
10 | * See examples of use of this library in course/edit.php and course/edit_form.php |
11 | * |
12 | * A few notes : |
13 | * form defintion is used for both printing of form and processing and should be the same |
14 | * for both or you may lose some submitted data which won't be let through. |
15 | * you should be using setType for every form element except select, radio or checkbox |
16 | * elements, these elements clean themselves. |
17 | * |
18 | * |
da6f8763 |
19 | * @author Jamie Pratt |
20 | * @version $Id$ |
21 | * @license http://www.gnu.org/copyleft/gpl.html GNU Public License |
22 | */ |
23 | |
24 | //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else. |
25 | if (FALSE===strstr(ini_get('include_path'), $CFG->libdir.'/pear' )){ |
26 | ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path')); |
27 | } |
28 | require_once 'HTML/QuickForm.php'; |
29 | require_once 'HTML/QuickForm/DHTMLRulesTableless.php'; |
30 | require_once 'HTML/QuickForm/Renderer/Tableless.php'; |
31 | |
49292f8c |
32 | require_once $CFG->libdir.'/uploadlib.php'; |
33 | |
a23f0aaf |
34 | /** |
35 | * Callback called when PEAR throws an error |
36 | * |
37 | * @param PEAR_Error $error |
38 | */ |
39 | function pear_handle_error($error){ |
40 | echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo(); |
41 | echo '<br /> <strong>Backtrace </strong>:'; |
42 | print_object($error->backtrace); |
43 | } |
44 | |
864cc1de |
45 | if ($CFG->debug >= DEBUG_ALL){ |
a23f0aaf |
46 | PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error'); |
864cc1de |
47 | } |
48 | |
f07b9627 |
49 | |
05f5c40c |
50 | /** |
da1320da |
51 | * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly |
52 | * use this class you should write a class defintion which extends this class or a more specific |
53 | * subclass such a moodleform_mod for each form you want to display and/or process with formslib. |
54 | * |
55 | * You will write your own definition() method which performs the form set up. |
05f5c40c |
56 | */ |
7f40a229 |
57 | class moodleform { |
49292f8c |
58 | var $_formname; // form name |
3c7656b4 |
59 | /** |
60 | * quickform object definition |
61 | * |
62 | * @var MoodleQuickForm |
63 | */ |
64 | var $_form; |
65 | /** |
66 | * globals workaround |
67 | * |
68 | * @var array |
69 | */ |
70 | var $_customdata; |
71 | /** |
72 | * file upload manager |
73 | * |
74 | * @var upload_manager |
75 | */ |
76 | var $_upload_manager; // |
4f51f48f |
77 | /** |
78 | * definition_after_data executed flag |
79 | * @var definition_finalized |
80 | */ |
81 | var $_definition_finalized = false; |
ebd3c7ac |
82 | |
da1320da |
83 | /** |
84 | * The constructor function calls the abstract function definition() and it will then |
85 | * process and clean and attempt to validate incoming data. |
86 | * |
87 | * It will call your custom validate method to validate data and will also check any rules |
88 | * you have specified in definition using addRule |
89 | * |
90 | * The name of the form (id attribute of the form) is automatically generated depending on |
91 | * the name you gave the class extending moodleform. You should call your class something |
92 | * like |
93 | * |
4f51f48f |
94 | * @param mixed $action the action attribute for the form. If empty defaults to auto detect the |
95 | * current url. If a moodle_url object then outputs params as hidden variables. |
da1320da |
96 | * @param array $customdata if your form defintion method needs access to data such as $course |
97 | * $cm, etc. to construct the form definition then pass it in this array. You can |
98 | * use globals for somethings. |
99 | * @param string $method if you set this to anything other than 'post' then _GET and _POST will |
100 | * be merged and used as incoming data to the form. |
101 | * @param string $target target frame for form submission. You will rarely use this. Don't use |
102 | * it if you don't need to as the target attribute is deprecated in xhtml |
103 | * strict. |
104 | * @param mixed $attributes you can pass a string of html attributes here or an array. |
105 | * @return moodleform |
106 | */ |
4f51f48f |
107 | function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) { |
a23f0aaf |
108 | if (empty($action)){ |
109 | $action = strip_querystring(qualified_me()); |
110 | } |
f07b9627 |
111 | |
72f46d11 |
112 | $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element |
7f40a229 |
113 | $this->_customdata = $customdata; |
5bc97c98 |
114 | $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes); |
4f51f48f |
115 | if (!$editable){ |
116 | $this->_form->hardFreeze(); |
117 | } |
feaf5d06 |
118 | $this->set_upload_manager(new upload_manager()); |
7f40a229 |
119 | |
120 | $this->definition(); |
121 | |
122 | $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection |
123 | $this->_form->setDefault('sesskey', sesskey()); |
5bc97c98 |
124 | $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker |
125 | $this->_form->setDefault('_qf__'.$this->_formname, 1); |
126 | $this->_form->_setDefaultRuleMessages(); |
7f40a229 |
127 | |
128 | // we have to know all input types before processing submission ;-) |
129 | $this->_process_submission($method); |
7f40a229 |
130 | } |
05f5c40c |
131 | |
2c412890 |
132 | /** |
da1320da |
133 | * To autofocus on first form element or first element with error. |
2c412890 |
134 | * |
8dec2253 |
135 | * @param string $name if this is set then the focus is forced to a field with this name |
136 | * |
2c412890 |
137 | * @return string javascript to select form element with first error or |
da1320da |
138 | * first element if no errors. Use this as a parameter |
139 | * when calling print_header |
2c412890 |
140 | */ |
46f3921e |
141 | function focus($name=NULL) { |
9403060a |
142 | $form =& $this->_form; |
46f3921e |
143 | $elkeys = array_keys($form->_elementIndex); |
144 | $error = false; |
9403060a |
145 | if (isset($form->_errors) && 0 != count($form->_errors)){ |
146 | $errorkeys = array_keys($form->_errors); |
147 | $elkeys = array_intersect($elkeys, $errorkeys); |
46f3921e |
148 | $error = true; |
2c412890 |
149 | } |
46f3921e |
150 | |
151 | if ($error or empty($name)) { |
152 | $names = array(); |
153 | while (empty($names) and !empty($elkeys)) { |
154 | $el = array_shift($elkeys); |
155 | $names = $form->_getElNamesRecursive($el); |
156 | } |
157 | if (!empty($names)) { |
158 | $name = array_shift($names); |
159 | } |
8dec2253 |
160 | } |
46f3921e |
161 | |
162 | $focus = ''; |
163 | if (!empty($name)) { |
164 | $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']'; |
9403060a |
165 | } |
46f3921e |
166 | |
9403060a |
167 | return $focus; |
168 | } |
7f40a229 |
169 | |
05f5c40c |
170 | /** |
171 | * Internal method. Alters submitted data to be suitable for quickforms processing. |
172 | * Must be called when the form is fully set up. |
173 | */ |
7f40a229 |
174 | function _process_submission($method) { |
175 | $submission = array(); |
176 | if ($method == 'post') { |
177 | if (!empty($_POST)) { |
178 | $submission = $_POST; |
179 | } |
180 | } else { |
181 | $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param() |
182 | } |
183 | |
184 | // following trick is needed to enable proper sesskey checks when using GET forms |
5bc97c98 |
185 | // the _qf__.$this->_formname serves as a marker that form was actually submitted |
186 | if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) { |
7f40a229 |
187 | if (!confirm_sesskey()) { |
188 | error('Incorrect sesskey submitted, form not accepted!'); |
189 | } |
05f5c40c |
190 | $files = $_FILES; |
7f40a229 |
191 | } else { |
192 | $submission = array(); |
05f5c40c |
193 | $files = array(); |
7f40a229 |
194 | } |
195 | |
05f5c40c |
196 | $this->_form->updateSubmission($submission, $files); |
7f40a229 |
197 | } |
198 | |
05f5c40c |
199 | /** |
200 | * Internal method. Validates all uploaded files. |
201 | */ |
89489cfe |
202 | function _validate_files(&$files) { |
203 | $files = array(); |
204 | |
49292f8c |
205 | if (empty($_FILES)) { |
206 | // we do not need to do any checks because no files were submitted |
89489cfe |
207 | // note: server side rules do not work for files - use custom verification in validate() instead |
49292f8c |
208 | return true; |
209 | } |
210 | $errors = array(); |
211 | $mform =& $this->_form; |
212 | |
49292f8c |
213 | // check the files |
214 | $status = $this->_upload_manager->preprocess_files(); |
215 | |
216 | // now check that we really want each file |
217 | foreach ($_FILES as $elname=>$file) { |
218 | if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') { |
219 | $required = $mform->isElementRequired($elname); |
220 | if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) { |
221 | if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) { |
222 | // file not uploaded and not required - ignore it |
223 | continue; |
224 | } |
225 | $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog']; |
89489cfe |
226 | |
bec52f19 |
227 | } else if (!empty($this->_upload_manager->files[$elname]['clear'])) { |
89489cfe |
228 | $files[$elname] = $this->_upload_manager->files[$elname]['tmp_name']; |
49292f8c |
229 | } |
230 | } else { |
feaf5d06 |
231 | error('Incorrect upload attempt!'); |
49292f8c |
232 | } |
233 | } |
234 | |
235 | // return errors if found |
236 | if ($status and 0 == count($errors)){ |
237 | return true; |
89489cfe |
238 | |
49292f8c |
239 | } else { |
89489cfe |
240 | $files = array(); |
49292f8c |
241 | return $errors; |
242 | } |
243 | } |
244 | |
05f5c40c |
245 | /** |
da1320da |
246 | * Load in existing data as form defaults. Usually new entry defaults are stored directly in |
247 | * form definition (new entry form); this function is used to load in data where values |
248 | * already exist and data is being edited (edit entry form). |
05f5c40c |
249 | * |
250 | * @param mixed $default_values object or array of default values |
251 | * @param bool $slased true if magic quotes applied to data values |
252 | */ |
beac4717 |
253 | function set_data($default_values, $slashed=false) { |
7f40a229 |
254 | if (is_object($default_values)) { |
255 | $default_values = (array)$default_values; |
256 | } |
257 | $filter = $slashed ? 'stripslashes' : NULL; |
258 | $this->_form->setDefaults($default_values, $filter); |
259 | } |
260 | |
c80a13c7 |
261 | /** |
feaf5d06 |
262 | * Set custom upload manager. |
c80a13c7 |
263 | * Must be used BEFORE creating of file element! |
264 | * |
feaf5d06 |
265 | * @param object $um - custom upload manager |
c80a13c7 |
266 | */ |
feaf5d06 |
267 | function set_upload_manager($um=false) { |
268 | if ($um === false) { |
269 | $um = new upload_manager(); |
c80a13c7 |
270 | } |
feaf5d06 |
271 | $this->_upload_manager = $um; |
c80a13c7 |
272 | |
feaf5d06 |
273 | $this->_form->setMaxFileSize($um->config->maxbytes); |
c80a13c7 |
274 | } |
275 | |
05f5c40c |
276 | /** |
277 | * Check that form was submitted. Does not check validity of submitted data. |
278 | * |
279 | * @return bool true if form properly submitted |
280 | */ |
7f40a229 |
281 | function is_submitted() { |
282 | return $this->_form->isSubmitted(); |
283 | } |
284 | |
a23f0aaf |
285 | function no_submit_button_pressed(){ |
286 | static $nosubmit = null; // one check is enough |
287 | if (!is_null($nosubmit)){ |
288 | return $nosubmit; |
289 | } |
290 | $mform =& $this->_form; |
291 | $nosubmit = false; |
f07b9627 |
292 | if (!$this->is_submitted()){ |
293 | return false; |
294 | } |
a23f0aaf |
295 | foreach ($mform->_noSubmitButtons as $nosubmitbutton){ |
296 | if (optional_param($nosubmitbutton, 0, PARAM_RAW)){ |
297 | $nosubmit = true; |
298 | break; |
299 | } |
300 | } |
301 | return $nosubmit; |
302 | } |
303 | |
304 | |
05f5c40c |
305 | /** |
306 | * Check that form data is valid. |
307 | * |
308 | * @return bool true if form data valid |
309 | */ |
7f40a229 |
310 | function is_validated() { |
49292f8c |
311 | static $validated = null; // one validation is enough |
3ba2c187 |
312 | $mform =& $this->_form; |
f07b9627 |
313 | |
4f51f48f |
314 | //finalize the form definition before any processing |
315 | if (!$this->_definition_finalized) { |
316 | $this->_definition_finalized = true; |
317 | $this->definition_after_data(); |
318 | } |
319 | |
9aa022fe |
320 | if ($this->no_submit_button_pressed()){ |
321 | return false; |
322 | } elseif ($validated === null) { |
3ba2c187 |
323 | $internal_val = $mform->validate(); |
89489cfe |
324 | |
325 | $files = array(); |
326 | $file_val = $this->_validate_files($files); |
327 | if ($file_val !== true) { |
328 | if (!empty($file_val)) { |
329 | foreach ($file_val as $element=>$msg) { |
330 | $mform->setElementError($element, $msg); |
331 | } |
332 | } |
333 | $file_val = false; |
334 | } |
335 | |
336 | $data = $mform->exportValues(null, true); |
337 | $moodle_val = $this->validation($data, $files); |
a78890d5 |
338 | if ((is_array($moodle_val) && count($moodle_val)!==0)) { |
339 | // non-empty array means errors |
340 | foreach ($moodle_val as $element=>$msg) { |
341 | $mform->setElementError($element, $msg); |
7f40a229 |
342 | } |
a78890d5 |
343 | $moodle_val = false; |
344 | |
345 | } else { |
346 | // anything else means validation ok |
347 | $moodle_val = true; |
7f40a229 |
348 | } |
89489cfe |
349 | |
49292f8c |
350 | $validated = ($internal_val and $moodle_val and $file_val); |
7f40a229 |
351 | } |
9aa022fe |
352 | return $validated; |
7f40a229 |
353 | } |
354 | |
19110c57 |
355 | /** |
356 | * Return true if a cancel button has been pressed resulting in the form being submitted. |
357 | * |
358 | * @return boolean true if a cancel button has been pressed |
359 | */ |
360 | function is_cancelled(){ |
361 | $mform =& $this->_form; |
a23f0aaf |
362 | if ($mform->isSubmitted()){ |
363 | foreach ($mform->_cancelButtons as $cancelbutton){ |
364 | if (optional_param($cancelbutton, 0, PARAM_RAW)){ |
365 | return true; |
366 | } |
19110c57 |
367 | } |
368 | } |
369 | return false; |
370 | } |
371 | |
05f5c40c |
372 | /** |
da1320da |
373 | * Return submitted data if properly submitted or returns NULL if validation fails or |
374 | * if there is no submitted data. |
05f5c40c |
375 | * |
376 | * @param bool $slashed true means return data with addslashes applied |
377 | * @return object submitted data; NULL if not valid or not submitted |
378 | */ |
beac4717 |
379 | function get_data($slashed=true) { |
19110c57 |
380 | $mform =& $this->_form; |
3ba2c187 |
381 | |
7f40a229 |
382 | if ($this->is_submitted() and $this->is_validated()) { |
19110c57 |
383 | $data = $mform->exportValues(null, $slashed); |
5bc97c98 |
384 | unset($data['sesskey']); // we do not need to return sesskey |
385 | unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too |
7f40a229 |
386 | if (empty($data)) { |
387 | return NULL; |
388 | } else { |
389 | return (object)$data; |
390 | } |
391 | } else { |
392 | return NULL; |
393 | } |
394 | } |
395 | |
4f51f48f |
396 | /** |
397 | * Return submitted data without validation or NULL if there is no submitted data. |
398 | * |
399 | * @param bool $slashed true means return data with addslashes applied |
400 | * @return object submitted data; NULL if not submitted |
401 | */ |
402 | function get_submitted_data($slashed=true) { |
403 | $mform =& $this->_form; |
404 | |
405 | if ($this->is_submitted()) { |
406 | $data = $mform->exportValues(null, $slashed); |
407 | unset($data['sesskey']); // we do not need to return sesskey |
408 | unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too |
409 | if (empty($data)) { |
410 | return NULL; |
411 | } else { |
412 | return (object)$data; |
413 | } |
414 | } else { |
415 | return NULL; |
416 | } |
417 | } |
418 | |
05f5c40c |
419 | /** |
420 | * Save verified uploaded files into directory. Upload process can be customised from definition() |
38f394b2 |
421 | * method by creating instance of upload manager and storing it in $this->_upload_form |
05f5c40c |
422 | * |
423 | * @param string $destination where to store uploaded files |
424 | * @return bool success |
425 | */ |
49292f8c |
426 | function save_files($destination) { |
49292f8c |
427 | if ($this->is_submitted() and $this->is_validated()) { |
428 | return $this->_upload_manager->save_files($destination); |
429 | } |
430 | return false; |
431 | } |
2b63df96 |
432 | |
feaf5d06 |
433 | /** |
434 | * If we're only handling one file (if inputname was given in the constructor) |
435 | * this will return the (possibly changed) filename of the file. |
436 | * @return mixed false in case of failure, string if ok |
437 | */ |
438 | function get_new_filename() { |
439 | return $this->_upload_manager->get_new_filename(); |
440 | } |
441 | |
b6b1d1ca |
442 | /** |
443 | * Get content of uploaded file. |
444 | * @param $element name of file upload element |
445 | * @return mixed false in case of failure, string if ok |
446 | */ |
447 | function get_file_content($elname) { |
448 | if (!$this->is_submitted() or !$this->is_validated()) { |
449 | return false; |
450 | } |
451 | |
452 | if (!$this->_form->elementExists($elname)) { |
453 | return false; |
454 | } |
455 | |
89489cfe |
456 | if (empty($this->_upload_manager->files[$elname]['clear'])) { |
457 | return false; |
458 | } |
459 | |
b6b1d1ca |
460 | if (empty($this->_upload_manager->files[$elname]['tmp_name'])) { |
461 | return false; |
89489cfe |
462 | } |
b6b1d1ca |
463 | |
89489cfe |
464 | $data = ""; |
465 | $file = @fopen($this->_upload_manager->files[$elname]['tmp_name'], "rb"); |
466 | if ($file) { |
467 | while (!feof($file)) { |
468 | $data .= fread($file, 1024); // TODO: do we really have to do this? |
b6b1d1ca |
469 | } |
89489cfe |
470 | fclose($file); |
471 | return $data; |
472 | } else { |
473 | return false; |
b6b1d1ca |
474 | } |
475 | } |
476 | |
05f5c40c |
477 | /** |
478 | * Print html form. |
479 | */ |
7f40a229 |
480 | function display() { |
4f51f48f |
481 | //finalize the form definition if not yet done |
482 | if (!$this->_definition_finalized) { |
483 | $this->_definition_finalized = true; |
484 | $this->definition_after_data(); |
485 | } |
7f40a229 |
486 | $this->_form->display(); |
487 | } |
488 | |
49292f8c |
489 | /** |
05f5c40c |
490 | * Abstract method - always override! |
49292f8c |
491 | * |
492 | * If you need special handling of uploaded files, create instance of $this->_upload_manager here. |
493 | */ |
7f40a229 |
494 | function definition() { |
495 | error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.'); |
496 | } |
2c412890 |
497 | |
c08ac016 |
498 | /** |
05f5c40c |
499 | * Dummy stub method - override if you need to setup the form depending on current |
beac4717 |
500 | * values. This method is called after definition(), data submission and set_data(). |
05f5c40c |
501 | * All form setup that is dependent on form values should go in here. |
c08ac016 |
502 | */ |
503 | function definition_after_data(){ |
c08ac016 |
504 | } |
7f40a229 |
505 | |
05f5c40c |
506 | /** |
507 | * Dummy stub method - override if you needed to perform some extra validation. |
508 | * If there are errors return array of errors ("fieldname"=>"error message"), |
509 | * otherwise true if ok. |
38f394b2 |
510 | * |
89489cfe |
511 | * Server side rules do not work for uploaded files, implement serverside rules here if needed. |
512 | * |
05f5c40c |
513 | * @param array $data array of ("fieldname"=>value) of submitted data |
89489cfe |
514 | * @param array $files array of uploaded files "element_name"=>tmp_file_path |
a78890d5 |
515 | * @return array of "element_name"=>"error_description" if there are errors, |
516 | * or an empty array if everything is OK (true allowed for backwards compatibility too). |
05f5c40c |
517 | */ |
89489cfe |
518 | function validation($data, $files) { |
13ccb7bd |
519 | return array(); |
7f40a229 |
520 | } |
ebd3c7ac |
521 | |
616b549a |
522 | /** |
523 | * Method to add a repeating group of elements to a form. |
524 | * |
525 | * @param array $elementobjs Array of elements or groups of elements that are to be repeated |
526 | * @param integer $repeats no of times to repeat elements initially |
527 | * @param array $options Array of options to apply to elements. Array keys are element names. |
528 | * This is an array of arrays. The second sets of keys are the option types |
529 | * for the elements : |
530 | * 'default' - default value is value |
531 | * 'type' - PARAM_* constant is value |
532 | * 'helpbutton' - helpbutton params array is value |
533 | * 'disabledif' - last three moodleform::disabledIf() |
534 | * params are value as an array |
535 | * @param string $repeathiddenname name for hidden element storing no of repeats in this form |
536 | * @param string $addfieldsname name for button to add more fields |
537 | * @param int $addfieldsno how many fields to add at a time |
271ffe3f |
538 | * @param string $addstring name of button, {no} is replaced by no of blanks that will be added. |
6f3b54c8 |
539 | * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false. |
a23f0aaf |
540 | * @return int no of repeats of element in this page |
616b549a |
541 | */ |
6f3b54c8 |
542 | function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, |
543 | $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){ |
271ffe3f |
544 | if ($addstring===null){ |
545 | $addstring = get_string('addfields', 'form', $addfieldsno); |
546 | } else { |
547 | $addstring = str_ireplace('{no}', $addfieldsno, $addstring); |
548 | } |
ebd3c7ac |
549 | $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT); |
550 | $addfields = optional_param($addfieldsname, '', PARAM_TEXT); |
551 | if (!empty($addfields)){ |
552 | $repeats += $addfieldsno; |
553 | } |
ebd3c7ac |
554 | $mform =& $this->_form; |
a23f0aaf |
555 | $mform->registerNoSubmitButton($addfieldsname); |
ebd3c7ac |
556 | $mform->addElement('hidden', $repeathiddenname, $repeats); |
557 | //value not to be overridden by submitted value |
558 | $mform->setConstants(array($repeathiddenname=>$repeats)); |
559 | for ($i=0; $i<$repeats; $i++) { |
560 | foreach ($elementobjs as $elementobj){ |
271ffe3f |
561 | $elementclone = clone($elementobj); |
7b41a4a9 |
562 | $name = $elementclone->getName(); |
86aab05c |
563 | if (!empty($name)){ |
564 | $elementclone->setName($name."[$i]"); |
565 | } |
ebd3c7ac |
566 | if (is_a($elementclone, 'HTML_QuickForm_header')){ |
567 | $value=$elementclone->_text; |
271ffe3f |
568 | $elementclone->setValue(str_replace('{no}', ($i+1), $value)); |
569 | |
570 | } else { |
571 | $value=$elementclone->getLabel(); |
572 | $elementclone->setLabel(str_replace('{no}', ($i+1), $value)); |
ebd3c7ac |
573 | |
574 | } |
7b41a4a9 |
575 | |
ebd3c7ac |
576 | $mform->addElement($elementclone); |
577 | } |
578 | } |
579 | for ($i=0; $i<$repeats; $i++) { |
580 | foreach ($options as $elementname => $elementoptions){ |
581 | $pos=strpos($elementname, '['); |
582 | if ($pos!==FALSE){ |
583 | $realelementname = substr($elementname, 0, $pos+1)."[$i]"; |
584 | $realelementname .= substr($elementname, $pos+1); |
585 | }else { |
586 | $realelementname = $elementname."[$i]"; |
587 | } |
588 | foreach ($elementoptions as $option => $params){ |
589 | |
590 | switch ($option){ |
591 | case 'default' : |
592 | $mform->setDefault($realelementname, $params); |
593 | break; |
ebd3c7ac |
594 | case 'helpbutton' : |
595 | $mform->setHelpButton($realelementname, $params); |
596 | break; |
597 | case 'disabledif' : |
9aa022fe |
598 | $params = array_merge(array($realelementname), $params); |
599 | call_user_func_array(array(&$mform, 'disabledIf'), $params); |
600 | break; |
601 | case 'rule' : |
602 | if (is_string($params)){ |
603 | $params = array(null, $params, null, 'client'); |
604 | } |
605 | $params = array_merge(array($realelementname), $params); |
606 | call_user_func_array(array(&$mform, 'addRule'), $params); |
ebd3c7ac |
607 | break; |
608 | |
609 | } |
610 | } |
611 | } |
612 | } |
271ffe3f |
613 | $mform->addElement('submit', $addfieldsname, $addstring); |
a23f0aaf |
614 | |
6f3b54c8 |
615 | if (!$addbuttoninside) { |
616 | $mform->closeHeaderBefore($addfieldsname); |
617 | } |
ebd3c7ac |
618 | |
19194f82 |
619 | return $repeats; |
ebd3c7ac |
620 | } |
a23f0aaf |
621 | /** |
1d284fbd |
622 | * Use this method to a cancel and submit button to the end of your form. Pass a param of false |
a23f0aaf |
623 | * if you don't want a cancel button in your form. If you have a cancel button make sure you |
624 | * check for it being pressed using is_cancelled() and redirecting if it is true before trying to |
beac4717 |
625 | * get data with get_data(). |
a23f0aaf |
626 | * |
627 | * @param boolean $cancel whether to show cancel button, default true |
a23f0aaf |
628 | * @param string $submitlabel label for submit button, defaults to get_string('savechanges') |
629 | */ |
1d284fbd |
630 | function add_action_buttons($cancel = true, $submitlabel=null){ |
a23f0aaf |
631 | if (is_null($submitlabel)){ |
632 | $submitlabel = get_string('savechanges'); |
633 | } |
634 | $mform =& $this->_form; |
1d284fbd |
635 | if ($cancel){ |
636 | //when two elements we need a group |
a23f0aaf |
637 | $buttonarray=array(); |
638 | $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel); |
1d284fbd |
639 | $buttonarray[] = &$mform->createElement('cancel'); |
a23f0aaf |
640 | $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false); |
4f51f48f |
641 | $mform->closeHeaderBefore('buttonar'); |
a23f0aaf |
642 | } else { |
643 | //no group needed |
644 | $mform->addElement('submit', 'submitbutton', $submitlabel); |
4f51f48f |
645 | $mform->closeHeaderBefore('submitbutton'); |
a23f0aaf |
646 | } |
647 | } |
7f40a229 |
648 | } |
649 | |
da1320da |
650 | /** |
651 | * You never extend this class directly. The class methods of this class are available from |
652 | * the private $this->_form property on moodleform and it's children. You generally only |
653 | * call methods on this class from within abstract methods that you override on moodleform such |
654 | * as definition and definition_after_data |
655 | * |
656 | */ |
7f40a229 |
657 | class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless { |
658 | var $_types = array(); |
50ef8eb9 |
659 | var $_dependencies = array(); |
19110c57 |
660 | /** |
661 | * Array of buttons that if pressed do not result in the processing of the form. |
662 | * |
663 | * @var array |
664 | */ |
665 | var $_noSubmitButtons=array(); |
666 | /** |
667 | * Array of buttons that if pressed do not result in the processing of the form. |
668 | * |
669 | * @var array |
670 | */ |
671 | var $_cancelButtons=array(); |
7f40a229 |
672 | |
19194f82 |
673 | /** |
674 | * Array whose keys are element names. If the key exists this is a advanced element |
675 | * |
676 | * @var array |
677 | */ |
678 | var $_advancedElements = array(); |
679 | |
680 | /** |
681 | * Whether to display advanced elements (on page load) |
682 | * |
683 | * @var boolean |
684 | */ |
685 | var $_showAdvanced = null; |
686 | |
f07b9627 |
687 | /** |
688 | * The form name is derrived from the class name of the wrapper minus the trailing form |
689 | * It is a name with words joined by underscores whereas the id attribute is words joined by |
690 | * underscores. |
691 | * |
692 | * @var unknown_type |
693 | */ |
694 | var $_formName = ''; |
43914931 |
695 | |
4f51f48f |
696 | /** |
697 | * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form. |
698 | * |
699 | * @var string |
700 | */ |
701 | var $_pageparams = ''; |
702 | |
da6f8763 |
703 | /** |
704 | * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless |
705 | * @param string $formName Form's name. |
706 | * @param string $method (optional)Form's method defaults to 'POST' |
4f51f48f |
707 | * @param mixed $action (optional)Form's action - string or moodle_url |
da6f8763 |
708 | * @param string $target (optional)Form's target defaults to none |
709 | * @param mixed $attributes (optional)Extra attributes for <form> tag |
710 | * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field |
711 | * @access public |
712 | */ |
7f40a229 |
713 | function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){ |
dcf6d93c |
714 | global $CFG; |
715 | |
271ffe3f |
716 | static $formcounter = 1; |
7f40a229 |
717 | |
da6f8763 |
718 | HTML_Common::HTML_Common($attributes); |
da6f8763 |
719 | $target = empty($target) ? array() : array('target' => $target); |
f07b9627 |
720 | $this->_formName = $formName; |
4f51f48f |
721 | if (is_a($action, 'moodle_url')){ |
722 | $this->_pageparams = $action->hidden_params_out(); |
723 | $action = $action->out(true); |
724 | } else { |
725 | $this->_pageparams = ''; |
726 | } |
da6f8763 |
727 | //no 'name' atttribute for form in xhtml strict : |
271ffe3f |
728 | $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target; |
729 | $formcounter++; |
da6f8763 |
730 | $this->updateAttributes($attributes); |
da6f8763 |
731 | |
7f40a229 |
732 | //this is custom stuff for Moodle : |
da6f8763 |
733 | $oldclass= $this->getAttribute('class'); |
734 | if (!empty($oldclass)){ |
735 | $this->updateAttributes(array('class'=>$oldclass.' mform')); |
736 | }else { |
80f962df |
737 | $this->updateAttributes(array('class'=>'mform')); |
da6f8763 |
738 | } |
653f890d |
739 | $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'; |
740 | $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />'; |
5bff0855 |
741 | $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />')); |
742 | //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true)); |
19194f82 |
743 | } |
744 | |
a23f0aaf |
745 | /** |
746 | * Use this method to indicate an element in a form is an advanced field. If items in a form |
747 | * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the |
748 | * form so the user can decide whether to display advanced form controls. |
749 | * |
750 | * If you set a header element to advanced then all elements it contains will also be set as advanced. |
751 | * |
752 | * @param string $elementName group or element name (not the element name of something inside a group). |
753 | * @param boolean $advanced default true sets the element to advanced. False removes advanced mark. |
754 | */ |
755 | function setAdvanced($elementName, $advanced=true){ |
756 | if ($advanced){ |
757 | $this->_advancedElements[$elementName]=''; |
758 | } elseif (isset($this->_advancedElements[$elementName])) { |
759 | unset($this->_advancedElements[$elementName]); |
760 | } |
761 | if ($advanced && $this->getElementType('mform_showadvanced_last')===false){ |
762 | $this->setShowAdvanced(); |
763 | $this->registerNoSubmitButton('mform_showadvanced'); |
764 | |
765 | $this->addElement('hidden', 'mform_showadvanced_last'); |
766 | } |
767 | } |
768 | /** |
769 | * Set whether to show advanced elements in the form on first displaying form. Default is not to |
770 | * display advanced elements in the form until 'Show Advanced' is pressed. |
771 | * |
772 | * You can get the last state of the form and possibly save it for this user by using |
773 | * value 'mform_showadvanced_last' in submitted data. |
774 | * |
775 | * @param boolean $showadvancedNow |
776 | */ |
777 | function setShowAdvanced($showadvancedNow = null){ |
778 | if ($showadvancedNow === null){ |
779 | if ($this->_showAdvanced !== null){ |
780 | return; |
781 | } else { //if setShowAdvanced is called without any preference |
782 | //make the default to not show advanced elements. |
f07b9627 |
783 | $showadvancedNow = get_user_preferences( |
784 | moodle_strtolower($this->_formName.'_showadvanced', 0)); |
a23f0aaf |
785 | } |
a23f0aaf |
786 | } |
787 | //value of hidden element |
788 | $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT); |
789 | //value of button |
790 | $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW); |
791 | //toggle if button pressed or else stay the same |
792 | if ($hiddenLast == -1) { |
793 | $next = $showadvancedNow; |
794 | } elseif ($buttonPressed) { //toggle on button press |
795 | $next = !$hiddenLast; |
796 | } else { |
797 | $next = $hiddenLast; |
798 | } |
799 | $this->_showAdvanced = $next; |
f07b9627 |
800 | if ($showadvancedNow != $next){ |
801 | set_user_preference($this->_formName.'_showadvanced', $next); |
802 | } |
a23f0aaf |
803 | $this->setConstants(array('mform_showadvanced_last'=>$next)); |
19194f82 |
804 | } |
805 | function getShowAdvanced(){ |
806 | return $this->_showAdvanced; |
807 | } |
808 | |
19194f82 |
809 | |
810 | /** |
811 | * Accepts a renderer |
812 | * |
813 | * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object |
814 | * @since 3.0 |
815 | * @access public |
816 | * @return void |
817 | */ |
46f3921e |
818 | function accept(&$renderer) { |
19194f82 |
819 | if (method_exists($renderer, 'setAdvancedElements')){ |
820 | //check for visible fieldsets where all elements are advanced |
821 | //and mark these headers as advanced as well. |
822 | //And mark all elements in a advanced header as advanced |
823 | $stopFields = $renderer->getStopFieldSetElements(); |
824 | $lastHeader = null; |
825 | $lastHeaderAdvanced = false; |
826 | $anyAdvanced = false; |
827 | foreach (array_keys($this->_elements) as $elementIndex){ |
828 | $element =& $this->_elements[$elementIndex]; |
46f3921e |
829 | |
830 | // if closing header and any contained element was advanced then mark it as advanced |
19194f82 |
831 | if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){ |
46f3921e |
832 | if ($anyAdvanced && !is_null($lastHeader)){ |
19194f82 |
833 | $this->setAdvanced($lastHeader->getName()); |
834 | } |
835 | $lastHeaderAdvanced = false; |
46f3921e |
836 | unset($lastHeader); |
837 | $lastHeader = null; |
19194f82 |
838 | } elseif ($lastHeaderAdvanced) { |
839 | $this->setAdvanced($element->getName()); |
840 | } |
46f3921e |
841 | |
19194f82 |
842 | if ($element->getType()=='header'){ |
843 | $lastHeader =& $element; |
844 | $anyAdvanced = false; |
845 | $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]); |
846 | } elseif (isset($this->_advancedElements[$element->getName()])){ |
847 | $anyAdvanced = true; |
848 | } |
849 | } |
46f3921e |
850 | // the last header may not be closed yet... |
851 | if ($anyAdvanced && !is_null($lastHeader)){ |
852 | $this->setAdvanced($lastHeader->getName()); |
853 | } |
19194f82 |
854 | $renderer->setAdvancedElements($this->_advancedElements); |
19194f82 |
855 | |
19194f82 |
856 | } |
857 | parent::accept($renderer); |
858 | } |
859 | |
19194f82 |
860 | |
19194f82 |
861 | |
862 | function closeHeaderBefore($elementName){ |
863 | $renderer =& $this->defaultRenderer(); |
864 | $renderer->addStopFieldsetElements($elementName); |
da6f8763 |
865 | } |
bb40325e |
866 | |
da1320da |
867 | /** |
868 | * Should be used for all elements of a form except for select, radio and checkboxes which |
869 | * clean their own data. |
870 | * |
871 | * @param string $elementname |
872 | * @param integer $paramtype use the constants PARAM_*. |
873 | * * PARAM_CLEAN is deprecated and you should try to use a more specific type. |
874 | * * PARAM_TEXT should be used for cleaning data that is expected to be plain text. |
875 | * It will strip all html tags. But will still let tags for multilang support |
876 | * through. |
877 | * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the |
878 | * html editor. Data from the editor is later cleaned before display using |
879 | * format_text() function. PARAM_RAW can also be used for data that is validated |
880 | * by some other way or printed by p() or s(). |
881 | * * PARAM_INT should be used for integers. |
882 | * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying |
883 | * form actions. |
884 | */ |
7f40a229 |
885 | function setType($elementname, $paramtype) { |
886 | $this->_types[$elementname] = $paramtype; |
887 | } |
49292f8c |
888 | |
da1320da |
889 | /** |
890 | * See description of setType above. This can be used to set several types at once. |
891 | * |
892 | * @param array $paramtypes |
893 | */ |
c56f1826 |
894 | function setTypes($paramtypes) { |
895 | $this->_types = $paramtypes + $this->_types; |
896 | } |
49292f8c |
897 | |
898 | function updateSubmission($submission, $files) { |
899 | $this->_flagSubmitted = false; |
900 | |
7f40a229 |
901 | if (empty($submission)) { |
902 | $this->_submitValues = array(); |
7f40a229 |
903 | } else { |
904 | foreach ($submission as $key=>$s) { |
905 | if (array_key_exists($key, $this->_types)) { |
906 | $submission[$key] = clean_param($s, $this->_types[$key]); |
907 | } |
908 | } |
909 | $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission); |
910 | $this->_flagSubmitted = true; |
911 | } |
912 | |
49292f8c |
913 | if (empty($files)) { |
914 | $this->_submitFiles = array(); |
915 | } else { |
916 | if (1 == get_magic_quotes_gpc()) { |
3a298174 |
917 | foreach (array_keys($files) as $elname) { |
49292f8c |
918 | // dangerous characters in filenames are cleaned later in upload_manager |
919 | $files[$elname]['name'] = stripslashes($files[$elname]['name']); |
920 | } |
921 | } |
922 | $this->_submitFiles = $files; |
923 | $this->_flagSubmitted = true; |
924 | } |
925 | |
2c412890 |
926 | // need to tell all elements that they need to update their value attribute. |
927 | foreach (array_keys($this->_elements) as $key) { |
928 | $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this); |
929 | } |
7f40a229 |
930 | } |
931 | |
da6f8763 |
932 | function getReqHTML(){ |
933 | return $this->_reqHTML; |
934 | } |
7f40a229 |
935 | |
19194f82 |
936 | function getAdvancedHTML(){ |
937 | return $this->_advancedHTML; |
938 | } |
939 | |
7f40a229 |
940 | /** |
da1320da |
941 | * Initializes a default form value. Used to specify the default for a new entry where |
beac4717 |
942 | * no data is loaded in using moodleform::set_data() |
7f40a229 |
943 | * |
944 | * @param string $elementname element name |
945 | * @param mixed $values values for that element name |
946 | * @param bool $slashed the default value is slashed |
947 | * @access public |
948 | * @return void |
949 | */ |
950 | function setDefault($elementName, $defaultValue, $slashed=false){ |
951 | $filter = $slashed ? 'stripslashes' : NULL; |
952 | $this->setDefaults(array($elementName=>$defaultValue), $filter); |
953 | } // end func setDefault |
da6f8763 |
954 | /** |
c56f1826 |
955 | * Add an array of buttons to the form |
7f40a229 |
956 | * @param array $buttons An associative array representing help button to attach to |
da6f8763 |
957 | * to the form. keys of array correspond to names of elements in form. |
7f40a229 |
958 | * |
da6f8763 |
959 | * @access public |
960 | */ |
d4fe14d3 |
961 | function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){ |
7f40a229 |
962 | |
c56f1826 |
963 | foreach ($buttons as $elementname => $button){ |
d4fe14d3 |
964 | $this->setHelpButton($elementname, $button, $suppresscheck, $function); |
da6f8763 |
965 | } |
966 | } |
c56f1826 |
967 | /** |
da1320da |
968 | * Add a single button. |
c56f1826 |
969 | * |
970 | * @param string $elementname name of the element to add the item to |
d4fe14d3 |
971 | * @param array $button - arguments to pass to function $function |
c56f1826 |
972 | * @param boolean $suppresscheck - whether to throw an error if the element |
973 | * doesn't exist. |
d4fe14d3 |
974 | * @param string $function - function to generate html from the arguments in $button |
c56f1826 |
975 | */ |
d4fe14d3 |
976 | function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){ |
c56f1826 |
977 | if (array_key_exists($elementname, $this->_elementIndex)){ |
978 | //_elements has a numeric index, this code accesses the elements by name |
979 | $element=&$this->_elements[$this->_elementIndex[$elementname]]; |
980 | if (method_exists($element, 'setHelpButton')){ |
d4fe14d3 |
981 | $element->setHelpButton($button, $function); |
c56f1826 |
982 | }else{ |
983 | $a=new object(); |
984 | $a->name=$element->getName(); |
985 | $a->classname=get_class($element); |
986 | print_error('nomethodforaddinghelpbutton', 'form', '', $a); |
987 | } |
988 | }elseif (!$suppresscheck){ |
989 | print_error('nonexistentformelements', 'form', '', $elementname); |
2c412890 |
990 | } |
c56f1826 |
991 | } |
7f40a229 |
992 | |
42f248e6 |
993 | function exportValues($elementList= null, $addslashes=true){ |
0ffb4cc7 |
994 | $unfiltered = array(); |
995 | if (null === $elementList) { |
996 | // iterate over all elements, calling their exportValue() methods |
98af2d1d |
997 | $emptyarray = array(); |
0ffb4cc7 |
998 | foreach (array_keys($this->_elements) as $key) { |
999 | if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){ |
98af2d1d |
1000 | $value = $this->_elements[$key]->exportValue($emptyarray, true); |
0ffb4cc7 |
1001 | } else { |
1002 | $value = $this->_elements[$key]->exportValue($this->_submitValues, true); |
1003 | } |
1004 | |
1005 | if (is_array($value)) { |
1006 | // This shit throws a bogus warning in PHP 4.3.x |
1007 | $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value); |
1008 | } |
1009 | } |
1010 | } else { |
1011 | if (!is_array($elementList)) { |
1012 | $elementList = array_map('trim', explode(',', $elementList)); |
1013 | } |
1014 | foreach ($elementList as $elementName) { |
1015 | $value = $this->exportValue($elementName); |
1016 | if (PEAR::isError($value)) { |
1017 | return $value; |
1018 | } |
1019 | $unfiltered[$elementName] = $value; |
1020 | } |
1021 | } |
7f40a229 |
1022 | |
da6f8763 |
1023 | if ($addslashes){ |
0ffb4cc7 |
1024 | return $this->_recursiveFilter('addslashes', $unfiltered); |
da6f8763 |
1025 | } else { |
1026 | return $unfiltered; |
1027 | } |
1028 | } |
f07b9627 |
1029 | /** |
1030 | * Adds a validation rule for the given field |
1031 | * |
1032 | * If the element is in fact a group, it will be considered as a whole. |
1033 | * To validate grouped elements as separated entities, |
1034 | * use addGroupRule instead of addRule. |
1035 | * |
1036 | * @param string $element Form element name |
1037 | * @param string $message Message to display for invalid data |
1038 | * @param string $type Rule type, use getRegisteredRules() to get types |
1039 | * @param string $format (optional)Required for extra rule data |
1040 | * @param string $validation (optional)Where to perform validation: "server", "client" |
1041 | * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error? |
1042 | * @param boolean $force Force the rule to be applied, even if the target form element does not exist |
1043 | * @since 1.0 |
1044 | * @access public |
1045 | * @throws HTML_QuickForm_Error |
1046 | */ |
1047 | function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false) |
1048 | { |
1049 | parent::addRule($element, $message, $type, $format, $validation, $reset, $force); |
1050 | if ($validation == 'client') { |
1051 | $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);')); |
1052 | } |
1053 | |
1054 | } // end func addRule |
1055 | /** |
1056 | * Adds a validation rule for the given group of elements |
1057 | * |
1058 | * Only groups with a name can be assigned a validation rule |
1059 | * Use addGroupRule when you need to validate elements inside the group. |
1060 | * Use addRule if you need to validate the group as a whole. In this case, |
1061 | * the same rule will be applied to all elements in the group. |
1062 | * Use addRule if you need to validate the group against a function. |
1063 | * |
1064 | * @param string $group Form group name |
1065 | * @param mixed $arg1 Array for multiple elements or error message string for one element |
1066 | * @param string $type (optional)Rule type use getRegisteredRules() to get types |
1067 | * @param string $format (optional)Required for extra rule data |
1068 | * @param int $howmany (optional)How many valid elements should be in the group |
1069 | * @param string $validation (optional)Where to perform validation: "server", "client" |
1070 | * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed. |
1071 | * @since 2.5 |
1072 | * @access public |
1073 | * @throws HTML_QuickForm_Error |
1074 | */ |
1075 | function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false) |
1076 | { |
1077 | parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset); |
1078 | if (is_array($arg1)) { |
3a298174 |
1079 | foreach ($arg1 as $rules) { |
f07b9627 |
1080 | foreach ($rules as $rule) { |
1081 | $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server'; |
1082 | |
1083 | if ('client' == $validation) { |
1084 | $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);')); |
1085 | } |
1086 | } |
1087 | } |
1088 | } elseif (is_string($arg1)) { |
1089 | |
1090 | if ($validation == 'client') { |
3a298174 |
1091 | $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);')); |
f07b9627 |
1092 | } |
1093 | } |
1094 | } // end func addGroupRule |
1095 | |
1096 | // }}} |
5bc97c98 |
1097 | /** |
1098 | * Returns the client side validation script |
1099 | * |
1100 | * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm |
1101 | * and slightly modified to run rules per-element |
1102 | * Needed to override this because of an error with client side validation of grouped elements. |
1103 | * |
1104 | * @access public |
1105 | * @return string Javascript to perform validation, empty string if no 'client' rules were added |
1106 | */ |
1107 | function getValidationScript() |
1108 | { |
1109 | if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) { |
1110 | return ''; |
1111 | } |
1112 | |
1113 | include_once('HTML/QuickForm/RuleRegistry.php'); |
1114 | $registry =& HTML_QuickForm_RuleRegistry::singleton(); |
1115 | $test = array(); |
1116 | $js_escape = array( |
1117 | "\r" => '\r', |
1118 | "\n" => '\n', |
1119 | "\t" => '\t', |
1120 | "'" => "\\'", |
1121 | '"' => '\"', |
1122 | '\\' => '\\\\' |
1123 | ); |
1124 | |
1125 | foreach ($this->_rules as $elementName => $rules) { |
1126 | foreach ($rules as $rule) { |
1127 | if ('client' == $rule['validation']) { |
da1320da |
1128 | unset($element); //TODO: find out how to properly initialize it |
5bc97c98 |
1129 | |
1130 | $dependent = isset($rule['dependent']) && is_array($rule['dependent']); |
1131 | $rule['message'] = strtr($rule['message'], $js_escape); |
1132 | |
1133 | if (isset($rule['group'])) { |
1134 | $group =& $this->getElement($rule['group']); |
1135 | // No JavaScript validation for frozen elements |
1136 | if ($group->isFrozen()) { |
1137 | continue 2; |
1138 | } |
1139 | $elements =& $group->getElements(); |
1140 | foreach (array_keys($elements) as $key) { |
1141 | if ($elementName == $group->getElementName($key)) { |
1142 | $element =& $elements[$key]; |
1143 | break; |
1144 | } |
1145 | } |
1146 | } elseif ($dependent) { |
1147 | $element = array(); |
1148 | $element[] =& $this->getElement($elementName); |
3a298174 |
1149 | foreach ($rule['dependent'] as $elName) { |
5bc97c98 |
1150 | $element[] =& $this->getElement($elName); |
1151 | } |
1152 | } else { |
1153 | $element =& $this->getElement($elementName); |
1154 | } |
1155 | // No JavaScript validation for frozen elements |
1156 | if (is_object($element) && $element->isFrozen()) { |
1157 | continue 2; |
1158 | } elseif (is_array($element)) { |
1159 | foreach (array_keys($element) as $key) { |
1160 | if ($element[$key]->isFrozen()) { |
1161 | continue 3; |
1162 | } |
1163 | } |
1164 | } |
1165 | // Fix for bug displaying errors for elements in a group |
1166 | //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule); |
1167 | $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule); |
1168 | $test[$elementName][1]=$element; |
1169 | //end of fix |
1170 | } |
1171 | } |
1172 | } |
7c77033f |
1173 | |
1174 | // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in |
1175 | // the form, and then that form field gets corrupted by the code that follows. |
1176 | unset($element); |
1177 | |
5bc97c98 |
1178 | $js = ' |
1179 | <script type="text/javascript"> |
1180 | //<![CDATA[ |
1cbb09f1 |
1181 | |
1182 | var skipClientValidation = false; |
1183 | |
5bc97c98 |
1184 | function qf_errorHandler(element, _qfMsg) { |
1185 | div = element.parentNode; |
1186 | if (_qfMsg != \'\') { |
e35c9eeb |
1187 | var errorSpan = document.getElementById(\'id_error_\'+element.name); |
e7004d05 |
1188 | if (!errorSpan) { |
1189 | errorSpan = document.createElement("span"); |
e35c9eeb |
1190 | errorSpan.id = \'id_error_\'+element.name; |
1191 | errorSpan.className = "error"; |
fed13a5e |
1192 | element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild); |
5bc97c98 |
1193 | } |
fed13a5e |
1194 | |
e7004d05 |
1195 | while (errorSpan.firstChild) { |
1196 | errorSpan.removeChild(errorSpan.firstChild); |
5bc97c98 |
1197 | } |
2c412890 |
1198 | |
e7004d05 |
1199 | errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3))); |
e35c9eeb |
1200 | errorSpan.appendChild(document.createElement("br")); |
5bc97c98 |
1201 | |
1202 | if (div.className.substr(div.className.length - 6, 6) != " error" |
1203 | && div.className != "error") { |
1204 | div.className += " error"; |
1205 | } |
1206 | |
1207 | return false; |
1208 | } else { |
e35c9eeb |
1209 | var errorSpan = document.getElementById(\'id_error_\'+element.name); |
e7004d05 |
1210 | if (errorSpan) { |
1211 | errorSpan.parentNode.removeChild(errorSpan); |
5bc97c98 |
1212 | } |
1213 | |
1214 | if (div.className.substr(div.className.length - 6, 6) == " error") { |
1215 | div.className = div.className.substr(0, div.className.length - 6); |
1216 | } else if (div.className == "error") { |
1217 | div.className = ""; |
1218 | } |
1219 | |
1220 | return true; |
1221 | } |
1222 | }'; |
1223 | $validateJS = ''; |
1224 | foreach ($test as $elementName => $jsandelement) { |
1225 | // Fix for bug displaying errors for elements in a group |
1226 | //unset($element); |
1227 | list($jsArr,$element)=$jsandelement; |
1228 | //end of fix |
1229 | $js .= ' |
f07b9627 |
1230 | function validate_' . $this->_formName . '_' . $elementName . '(element) { |
5bc97c98 |
1231 | var value = \'\'; |
1232 | var errFlag = new Array(); |
1233 | var _qfGroups = {}; |
1234 | var _qfMsg = \'\'; |
1235 | var frm = element.parentNode; |
1236 | while (frm && frm.nodeName != "FORM") { |
1237 | frm = frm.parentNode; |
1238 | } |
1239 | ' . join("\n", $jsArr) . ' |
1240 | return qf_errorHandler(element, _qfMsg); |
1241 | } |
1242 | '; |
1243 | $validateJS .= ' |
2ef7c374 |
1244 | ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret; |
1245 | if (!ret && !first_focus) { |
1246 | first_focus = true; |
1247 | frm.elements[\''.$elementName.'\'].focus(); |
1248 | } |
1249 | '; |
4f51f48f |
1250 | |
5bc97c98 |
1251 | // Fix for bug displaying errors for elements in a group |
1252 | //unset($element); |
1253 | //$element =& $this->getElement($elementName); |
1254 | //end of fix |
f07b9627 |
1255 | $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)'; |
5bc97c98 |
1256 | $onBlur = $element->getAttribute('onBlur'); |
1257 | $onChange = $element->getAttribute('onChange'); |
1258 | $element->updateAttributes(array('onBlur' => $onBlur . $valFunc, |
1259 | 'onChange' => $onChange . $valFunc)); |
1260 | } |
e7004d05 |
1261 | // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method |
5bc97c98 |
1262 | $js .= ' |
f07b9627 |
1263 | function validate_' . $this->_formName . '(frm) { |
1cbb09f1 |
1264 | if (skipClientValidation) { |
1265 | return true; |
1266 | } |
5bc97c98 |
1267 | var ret = true; |
4f51f48f |
1268 | |
0befbdfd |
1269 | var frm = document.getElementById(\''. $this->_attributes['id'] .'\') |
2ef7c374 |
1270 | var first_focus = false; |
5bc97c98 |
1271 | ' . $validateJS . '; |
1272 | return ret; |
1273 | } |
1274 | //]]> |
1275 | </script>'; |
1276 | return $js; |
1277 | } // end func getValidationScript |
1278 | function _setDefaultRuleMessages(){ |
1279 | foreach ($this->_rules as $field => $rulesarr){ |
1280 | foreach ($rulesarr as $key => $rule){ |
1281 | if ($rule['message']===null){ |
1282 | $a=new object(); |
1283 | $a->format=$rule['format']; |
1284 | $str=get_string('err_'.$rule['type'], 'form', $a); |
1285 | if (strpos($str, '[[')!==0){ |
1286 | $this->_rules[$field][$key]['message']=$str; |
2c412890 |
1287 | } |
5bc97c98 |
1288 | } |
1289 | } |
1290 | } |
1291 | } |
bb40325e |
1292 | |
d01a38cb |
1293 | function getLockOptionEndScript(){ |
dd07bbac |
1294 | |
1295 | $iname = $this->getAttribute('id').'items'; |
f4ba7e1a |
1296 | $js = '<script type="text/javascript">'."\n"; |
5e87b920 |
1297 | $js .= '//<![CDATA['."\n"; |
dd07bbac |
1298 | $js .= "var $iname = Array();\n"; |
1299 | |
1300 | foreach ($this->_dependencies as $dependentOn => $conditions){ |
1301 | $js .= "{$iname}['$dependentOn'] = Array();\n"; |
1302 | foreach ($conditions as $condition=>$values) { |
1303 | $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n"; |
1304 | foreach ($values as $value=>$dependents) { |
1305 | $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n"; |
1306 | $i = 0; |
1307 | foreach ($dependents as $dependent) { |
1308 | $elements = $this->_getElNamesRecursive($dependent); |
46f3921e |
1309 | if (empty($elements)) { |
1310 | // probably element inside of some group |
1311 | $elements = array($dependent); |
1312 | } |
dd07bbac |
1313 | foreach($elements as $element) { |
1314 | if ($element == $dependentOn) { |
1315 | continue; |
1316 | } |
1317 | $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n"; |
1318 | $i++; |
1319 | } |
11f260f4 |
1320 | } |
1321 | } |
50ef8eb9 |
1322 | } |
dd07bbac |
1323 | } |
d01a38cb |
1324 | $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n"; |
5e87b920 |
1325 | $js .='//]]>'."\n"; |
50ef8eb9 |
1326 | $js .='</script>'."\n"; |
1327 | return $js; |
bb40325e |
1328 | } |
d01a38cb |
1329 | |
46f3921e |
1330 | function _getElNamesRecursive($element) { |
1331 | if (is_string($element)) { |
4f51f48f |
1332 | if (!$this->elementExists($element)) { |
1333 | return array(); |
1334 | } |
46f3921e |
1335 | $element = $this->getElement($element); |
d01a38cb |
1336 | } |
46f3921e |
1337 | |
1338 | if (is_a($element, 'HTML_QuickForm_group')) { |
1339 | $elsInGroup = $element->getElements(); |
9403060a |
1340 | $elNames = array(); |
d01a38cb |
1341 | foreach ($elsInGroup as $elInGroup){ |
e850ec48 |
1342 | if (is_a($elInGroup, 'HTML_QuickForm_group')) { |
1343 | // not sure if this would work - groups nested in groups |
1344 | $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup)); |
1345 | } else { |
1346 | $elNames[] = $element->getElementName($elInGroup->getName()); |
1347 | } |
d01a38cb |
1348 | } |
46f3921e |
1349 | |
1350 | } else if (is_a($element, 'HTML_QuickForm_header')) { |
1351 | return array(); |
1352 | |
1353 | } else if (is_a($element, 'HTML_QuickForm_hidden')) { |
1354 | return array(); |
1355 | |
1356 | } else if (method_exists($element, 'getPrivateName')) { |
1357 | return array($element->getPrivateName()); |
1358 | |
1359 | } else { |
1360 | $elNames = array($element->getName()); |
d01a38cb |
1361 | } |
d01a38cb |
1362 | |
46f3921e |
1363 | return $elNames; |
50ef8eb9 |
1364 | } |
46f3921e |
1365 | |
6e372b25 |
1366 | /** |
1367 | * Adds a dependency for $elementName which will be disabled if $condition is met. |
9403060a |
1368 | * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element |
1369 | * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element |
31a6c06c |
1370 | * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value |
1371 | * of the $dependentOn element is $condition (such as equal) to $value. |
6e372b25 |
1372 | * |
1373 | * @param string $elementName the name of the element which will be disabled |
1374 | * @param string $dependentOn the name of the element whose state will be checked for |
1375 | * condition |
1376 | * @param string $condition the condition to check |
19110c57 |
1377 | * @param mixed $value used in conjunction with condition. |
6e372b25 |
1378 | */ |
dd07bbac |
1379 | function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){ |
1380 | if (!array_key_exists($dependentOn, $this->_dependencies)) { |
1381 | $this->_dependencies[$dependentOn] = array(); |
1382 | } |
1383 | if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) { |
1384 | $this->_dependencies[$dependentOn][$condition] = array(); |
1385 | } |
1386 | if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) { |
1387 | $this->_dependencies[$dependentOn][$condition][$value] = array(); |
1388 | } |
1389 | $this->_dependencies[$dependentOn][$condition][$value][] = $elementName; |
bb40325e |
1390 | } |
dd07bbac |
1391 | |
a23f0aaf |
1392 | function registerNoSubmitButton($buttonname){ |
1393 | $this->_noSubmitButtons[]=$buttonname; |
1394 | } |
dd07bbac |
1395 | |
a23f0aaf |
1396 | function isNoSubmitButton($buttonname){ |
1397 | return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE); |
19110c57 |
1398 | } |
dd07bbac |
1399 | |
19110c57 |
1400 | function _registerCancelButton($addfieldsname){ |
1401 | $this->_cancelButtons[]=$addfieldsname; |
1402 | } |
acc9c3e0 |
1403 | /** |
1404 | * Displays elements without HTML input tags. |
1405 | * This method is different to freeze() in that it makes sure no hidden |
1406 | * elements are included in the form. And a 'hardFrozen' element's submitted value is |
1407 | * ignored. |
1408 | * |
4af06dda |
1409 | * This function also removes all previously defined rules. |
1410 | * |
acc9c3e0 |
1411 | * @param mixed $elementList array or string of element(s) to be frozen |
1412 | * @since 1.0 |
1413 | * @access public |
1414 | * @throws HTML_QuickForm_Error |
1415 | */ |
1416 | function hardFreeze($elementList=null) |
1417 | { |
1418 | if (!isset($elementList)) { |
1419 | $this->_freezeAll = true; |
1420 | $elementList = array(); |
1421 | } else { |
1422 | if (!is_array($elementList)) { |
1423 | $elementList = preg_split('/[ ]*,[ ]*/', $elementList); |
1424 | } |
1425 | $elementList = array_flip($elementList); |
1426 | } |
1427 | |
1428 | foreach (array_keys($this->_elements) as $key) { |
1429 | $name = $this->_elements[$key]->getName(); |
1430 | if ($this->_freezeAll || isset($elementList[$name])) { |
1431 | $this->_elements[$key]->freeze(); |
1432 | $this->_elements[$key]->setPersistantFreeze(false); |
1433 | unset($elementList[$name]); |
4af06dda |
1434 | |
1435 | // remove all rules |
1436 | $this->_rules[$name] = array(); |
1437 | // if field is required, remove the rule |
1438 | $unset = array_search($name, $this->_required); |
1439 | if ($unset !== false) { |
1440 | unset($this->_required[$unset]); |
1441 | } |
acc9c3e0 |
1442 | } |
1443 | } |
1444 | |
1445 | if (!empty($elementList)) { |
1446 | return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true); |
1447 | } |
1448 | return true; |
4f51f48f |
1449 | } |
1450 | /** |
1451 | * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form. |
1452 | * |
1453 | * This function also removes all previously defined rules of elements it freezes. |
1454 | * |
1455 | * @param array $elementList array or string of element(s) not to be frozen |
1456 | * @since 1.0 |
1457 | * @access public |
1458 | * @throws HTML_QuickForm_Error |
1459 | */ |
1460 | function hardFreezeAllVisibleExcept($elementList) |
1461 | { |
1462 | $elementList = array_flip($elementList); |
1463 | foreach (array_keys($this->_elements) as $key) { |
1464 | $name = $this->_elements[$key]->getName(); |
1465 | $type = $this->_elements[$key]->getType(); |
56015454 |
1466 | |
4f51f48f |
1467 | if ($type == 'hidden'){ |
1468 | // leave hidden types as they are |
1469 | } elseif (!isset($elementList[$name])) { |
1470 | $this->_elements[$key]->freeze(); |
1471 | $this->_elements[$key]->setPersistantFreeze(false); |
1472 | |
1473 | // remove all rules |
1474 | $this->_rules[$name] = array(); |
1475 | // if field is required, remove the rule |
1476 | $unset = array_search($name, $this->_required); |
1477 | if ($unset !== false) { |
1478 | unset($this->_required[$unset]); |
1479 | } |
1480 | } |
1481 | } |
1482 | return true; |
1483 | } |
1484 | /** |
1485 | * Tells whether the form was already submitted |
1486 | * |
1487 | * This is useful since the _submitFiles and _submitValues arrays |
1488 | * may be completely empty after the trackSubmit value is removed. |
1489 | * |
1490 | * @access public |
1491 | * @return bool |
1492 | */ |
1493 | function isSubmitted() |
1494 | { |
1495 | return parent::isSubmitted() && (!$this->isFrozen()); |
1496 | } |
da6f8763 |
1497 | } |
1498 | |
e24b7f85 |
1499 | |
da6f8763 |
1500 | /** |
7f40a229 |
1501 | * A renderer for MoodleQuickForm that only uses XHTML and CSS and no |
da6f8763 |
1502 | * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless |
7f40a229 |
1503 | * |
da6f8763 |
1504 | * Stylesheet is part of standard theme and should be automatically included. |
1505 | * |
1506 | * @author Jamie Pratt <me@jamiep.org> |
1507 | * @license gpl license |
1508 | */ |
7f40a229 |
1509 | class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{ |
da6f8763 |
1510 | |
1511 | /** |
1512 | * Element template array |
1513 | * @var array |
1514 | * @access private |
1515 | */ |
1516 | var $_elementTemplates; |
49c53687 |
1517 | /** |
1518 | * Template used when opening a hidden fieldset |
1519 | * (i.e. a fieldset that is opened when there is no header element) |
1520 | * @var string |
1521 | * @access private |
1522 | */ |
c02345e3 |
1523 | var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>"; |
19194f82 |
1524 | /** |
1525 | * Header Template string |
1526 | * @var string |
1527 | * @access private |
1528 | */ |
1529 | var $_headerTemplate = |
c02345e3 |
1530 | "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t"; |
7f40a229 |
1531 | |
49c53687 |
1532 | /** |
bc9ec4a6 |
1533 | * Template used when opening a fieldset |
1534 | * @var string |
1535 | * @access private |
1536 | */ |
1537 | var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>"; |
1538 | |
1539 | /** |
49c53687 |
1540 | * Template used when closing a fieldset |
1541 | * @var string |
1542 | * @access private |
1543 | */ |
c02345e3 |
1544 | var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>"; |
42f248e6 |
1545 | |
49c53687 |
1546 | /** |
1547 | * Required Note template string |
1548 | * @var string |
1549 | * @access private |
1550 | */ |
7f40a229 |
1551 | var $_requiredNoteTemplate = |
6ba2c73d |
1552 | "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>"; |
7f40a229 |
1553 | |
19194f82 |
1554 | var $_advancedElements = array(); |
1555 | |
1556 | /** |
1557 | * Whether to display advanced elements (on page load) |
1558 | * |
1559 | * @var integer 1 means show 0 means hide |
1560 | */ |
1561 | var $_showAdvanced; |
1562 | |
7f40a229 |
1563 | function MoodleQuickForm_Renderer(){ |
42f248e6 |
1564 | // switch next two lines for ol li containers for form items. |
49c7f3a8 |
1565 | // $this->_elementTemplates=array('default'=>"\n\t\t".'<li class="fitem"><label>{label}{help}<!-- BEGIN required -->{req}<!-- END required --></label><div class="qfelement<!-- BEGIN error --> error<!-- END error --> {type}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>'); |
9aa022fe |
1566 | $this->_elementTemplates = array( |
f8b9ac74 |
1567 | 'default'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>', |
49c7f3a8 |
1568 | |
f8b9ac74 |
1569 | 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fgrouplabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>', |
4f51f48f |
1570 | |
f8b9ac74 |
1571 | 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element} </div></div>', |
43914931 |
1572 | |
4f51f48f |
1573 | 'nodisplay'=>''); |
da6f8763 |
1574 | |
1575 | parent::HTML_QuickForm_Renderer_Tableless(); |
1576 | } |
7f40a229 |
1577 | |
19194f82 |
1578 | function setAdvancedElements($elements){ |
1579 | $this->_advancedElements = $elements; |
1580 | } |
1581 | |
1582 | /** |
1583 | * What to do when starting the form |
1584 | * |
1585 | * @param MoodleQuickForm $form |
1586 | */ |
da6f8763 |
1587 | function startForm(&$form){ |
9403060a |
1588 | $this->_reqHTML = $form->getReqHTML(); |
1589 | $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates); |
19194f82 |
1590 | $this->_advancedHTML = $form->getAdvancedHTML(); |
1591 | $this->_showAdvanced = $form->getShowAdvanced(); |
da6f8763 |
1592 | parent::startForm($form); |
4f51f48f |
1593 | if ($form->isFrozen()){ |
1594 | $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>"; |
1595 | } else { |
1596 | $this->_hiddenHtml .= $form->_pageparams; |
1597 | } |
1598 | |
1599 | |
da6f8763 |
1600 | } |
7f40a229 |
1601 | |
da6f8763 |
1602 | function startGroup(&$group, $required, $error){ |
1603 | if (method_exists($group, 'getElementTemplateType')){ |
e249661f |
1604 | $html = $this->_elementTemplates[$group->getElementTemplateType()]; |
da6f8763 |
1605 | }else{ |
1606 | $html = $this->_elementTemplates['default']; |
7f40a229 |
1607 | |
da6f8763 |
1608 | } |
19194f82 |
1609 | if ($this->_showAdvanced){ |
1610 | $advclass = ' advanced'; |
1611 | } else { |
1612 | $advclass = ' advanced hide'; |
1613 | } |
1614 | if (isset($this->_advancedElements[$group->getName()])){ |
1615 | $html =str_replace(' {advanced}', $advclass, $html); |
1616 | $html =str_replace('{advancedimg}', $this->_advancedHTML, $html); |
1617 | } else { |
1618 | $html =str_replace(' {advanced}', '', $html); |
1619 | $html =str_replace('{advancedimg}', '', $html); |
1620 | } |
da6f8763 |
1621 | if (method_exists($group, 'getHelpButton')){ |
1622 | $html =str_replace('{help}', $group->getHelpButton(), $html); |
1623 | }else{ |
1624 | $html =str_replace('{help}', '', $html); |
da6f8763 |
1625 | } |
e7004d05 |
1626 | $html =str_replace('{name}', $group->getName(), $html); |
49c53687 |
1627 | $html =str_replace('{type}', 'fgroup', $html); |
7f40a229 |
1628 | |
da6f8763 |
1629 | $this->_templates[$group->getName()]=$html; |
1630 | // Fix for bug in tableless quickforms that didn't allow you to stop a |
1631 | // fieldset before a group of elements. |
1632 | // if the element name indicates the end of a fieldset, close the fieldset |
1633 | if ( in_array($group->getName(), $this->_stopFieldsetElements) |
1634 | && $this->_fieldsetsOpen > 0 |
1635 | ) { |
1636 | $this->_html .= $this->_closeFieldsetTemplate; |
1637 | $this->_fieldsetsOpen--; |
1638 | } |
1639 | parent::startGroup($group, $required, $error); |
1640 | } |
7f40a229 |
1641 | |
da6f8763 |
1642 | function renderElement(&$element, $required, $error){ |
86aab05c |
1643 | //manipulate id of all elements before rendering |
1644 | if (!is_null($element->getAttribute('id'))) { |
1645 | $id = $element->getAttribute('id'); |
1646 | } else { |
1647 | $id = $element->getName(); |
1648 | } |
1649 | //strip qf_ prefix and replace '[' with '_' and strip ']' |
1650 | $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id); |
1651 | if (strpos($id, 'id_') !== 0){ |
1652 | $element->updateAttributes(array('id'=>'id_'.$id)); |
1653 | } |
1654 | |
1655 | //adding stuff to place holders in template |
da6f8763 |
1656 | if (method_exists($element, 'getElementTemplateType')){ |
1657 | $html = $this->_elementTemplates[$element->getElementTemplateType()]; |
1658 | }else{ |
1659 | $html = $this->_elementTemplates['default']; |
19194f82 |
1660 | } |
1661 | if ($this->_showAdvanced){ |
1662 | $advclass = ' advanced'; |
1663 | } else { |
1664 | $advclass = ' advanced hide'; |
1665 | } |
1666 | if (isset($this->_advancedElements[$element->getName()])){ |
1667 | $html =str_replace(' {advanced}', $advclass, $html); |
1668 | } else { |
1669 | $html =str_replace(' {advanced}', '', $html); |
1670 | } |
1671 | if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){ |
1672 | $html =str_replace('{advancedimg}', $this->_advancedHTML, $html); |
1673 | } else { |
1674 | $html =str_replace('{advancedimg}', '', $html); |
da6f8763 |
1675 | } |
49c53687 |
1676 | $html =str_replace('{type}', 'f'.$element->getType(), $html); |
e7004d05 |
1677 | $html =str_replace('{name}', $element->getName(), $html); |
da6f8763 |
1678 | if (method_exists($element, 'getHelpButton')){ |
9403060a |
1679 | $html = str_replace('{help}', $element->getHelpButton(), $html); |
da6f8763 |
1680 | }else{ |
9403060a |
1681 | $html = str_replace('{help}', '', $html); |
7f40a229 |
1682 | |
da6f8763 |
1683 | } |
41b6d001 |
1684 | if (!isset($this->_templates[$element->getName()])) { |
1685 | $this->_templates[$element->getName()] = $html; |
1686 | } |
86aab05c |
1687 | |
da6f8763 |
1688 | parent::renderElement($element, $required, $error); |
1689 | } |
19194f82 |
1690 | |
bb40325e |
1691 | function finishForm(&$form){ |
4f51f48f |
1692 | if ($form->isFrozen()){ |
1693 | $this->_hiddenHtml = ''; |
1694 | } |
bb40325e |
1695 | parent::finishForm($form); |
4f51f48f |
1696 | if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) { |
1697 | // add a lockoptions script |
bb40325e |
1698 | $this->_html = $this->_html . "\n" . $script; |
1699 | } |
1700 | } |
19194f82 |
1701 | /** |
1702 | * Called when visiting a header element |
1703 | * |
1704 | * @param object An HTML_QuickForm_header element being visited |
1705 | * @access public |
1706 | * @return void |
1707 | */ |
1708 | function renderHeader(&$header) { |
1709 | $name = $header->getName(); |
1710 | |
1711 | $id = empty($name) ? '' : ' id="' . $name . '"'; |
78354cec |
1712 | $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id); |
19194f82 |
1713 | if (is_null($header->_text)) { |
1714 | $header_html = ''; |
1715 | } elseif (!empty($name) && isset($this->_templates[$name])) { |
1716 | $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]); |
1717 | } else { |
1718 | $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate); |
1719 | } |
1720 | |
1721 | if (isset($this->_advancedElements[$name])){ |
1722 | $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html); |
1723 | } else { |
1724 | $header_html =str_replace('{advancedimg}', '', $header_html); |
1725 | } |
1726 | $elementName='mform_showadvanced'; |
1727 | if ($this->_showAdvanced==0){ |
1728 | $buttonlabel = get_string('showadvanced', 'form'); |
1729 | } else { |
1730 | $buttonlabel = get_string('hideadvanced', 'form'); |
1731 | } |
1732 | |
1733 | if (isset($this->_advancedElements[$name])){ |
7c9b1d31 |
1734 | // this is tricky - the first submit button on form is "clicked" if user presses enter |
1735 | // we do not want to "submit" using advanced button if javascript active |
19194f82 |
1736 | $showtext="'".get_string('showadvanced', 'form')."'"; |
1737 | $hidetext="'".get_string('hideadvanced', 'form')."'"; |
1738 | //onclick returns false so if js is on then page is not submitted. |
1739 | $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');'; |
7c9b1d31 |
1740 | $button_js = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="button" onclick="'.$onclick.'" />'; |
1741 | $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />'; |
1742 | $button = '<script type="text/javascript"> |
1743 | //<![CDATA[ |
1744 | document.write("'.addslashes_js($button_js).'") |
1745 | //]]> |
1746 | </script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation |
1747 | |
1748 | $header_html = str_replace('{button}', $button, $header_html); |
19194f82 |
1749 | } else { |
7c9b1d31 |
1750 | $header_html = str_replace('{button}', '', $header_html); |
19194f82 |
1751 | } |
1752 | |
1753 | if ($this->_fieldsetsOpen > 0) { |
1754 | $this->_html .= $this->_closeFieldsetTemplate; |
1755 | $this->_fieldsetsOpen--; |
1756 | } |
1757 | |
1758 | $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate); |
1759 | if ($this->_showAdvanced){ |
1760 | $advclass = ' class="advanced"'; |
1761 | } else { |
1762 | $advclass = ' class="advanced hide"'; |
1763 | } |
1764 | if (isset($this->_advancedElements[$name])){ |
1765 | $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate); |
1766 | } else { |
1767 | $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate); |
1768 | } |
1769 | $this->_html .= $openFieldsetTemplate . $header_html; |
1770 | $this->_fieldsetsOpen++; |
1771 | } // end func renderHeader |
1772 | |
1773 | function getStopFieldsetElements(){ |
1774 | return $this->_stopFieldsetElements; |
1775 | } |
da6f8763 |
1776 | } |
1777 | |
da6f8763 |
1778 | |
9403060a |
1779 | $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer(); |
da6f8763 |
1780 | |
7f40a229 |
1781 | MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox'); |
1782 | MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file'); |
1783 | MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group'); |
1784 | MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password'); |
4f51f48f |
1785 | MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask'); |
7f40a229 |
1786 | MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio'); |
1787 | MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select'); |
4f51f48f |
1788 | MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups'); |
8f9607db |
1789 | MoodleQuickForm::registerElementType('selectallornone', "$CFG->libdir/form/selectallornone.php", 'MoodleQuickForm_selectallornone'); |
7f40a229 |
1790 | MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text'); |
1791 | MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea'); |
1792 | MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector'); |
1793 | MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector'); |
1794 | MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor'); |
effa85f4 |
1795 | MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format'); |
7f40a229 |
1796 | MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static'); |
1797 | MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden'); |
e2294b98 |
1798 | MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible'); |
e0f40684 |
1799 | MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno'); |
d4fe14d3 |
1800 | MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade'); |
19110c57 |
1801 | MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel'); |
3c7656b4 |
1802 | MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button'); |
1803 | MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile'); |
6f05b1e1 |
1804 | MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo'); |
a23f0aaf |
1805 | MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header'); |
1806 | MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit'); |
9e93222d |
1807 | MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory'); |
111be766 |
1808 | MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox'); |
49c7f3a8 |
1809 | ?> |