Merge branch 'MDL-26435_rem_commented_out_code' of git://github.com/andyjdavis/moodle
[moodle.git] / lib / formslib.php
blobab03871cbbbdeff381602bb8ed504c607e5cc7c6
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
23 * and validation.
25 * See examples of use of this library in course/edit.php and course/edit_form.php
27 * A few notes :
28 * form definition is used for both printing of form and processing and should be the same
29 * for both or you may lose some submitted data which won't be let through.
30 * you should be using setType for every form element except select, radio or checkbox
31 * elements, these elements clean themselves.
34 * @copyright Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @package core
37 * @subpackage form
40 defined('MOODLE_INTERNAL') || die();
42 /** setup.php includes our hacked pear libs first */
43 require_once 'HTML/QuickForm.php';
44 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
45 require_once 'HTML/QuickForm/Renderer/Tableless.php';
47 require_once $CFG->libdir.'/filelib.php';
49 define('EDITOR_UNLIMITED_FILES', -1);
51 /**
52 * Callback called when PEAR throws an error
54 * @param PEAR_Error $error
56 function pear_handle_error($error){
57 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
58 echo '<br /> <strong>Backtrace </strong>:';
59 print_object($error->backtrace);
62 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
63 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
66 /**
68 * @staticvar bool $done
69 * @global moodle_page $PAGE
71 function form_init_date_js() {
72 global $PAGE;
73 static $done = false;
74 if (!$done) {
75 $module = 'moodle-form-dateselector';
76 $function = 'M.form.dateselector.init_date_selectors';
77 $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
78 $PAGE->requires->yui_module($module, $function, $config);
79 $done = true;
83 /**
84 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
85 * use this class you should write a class definition which extends this class or a more specific
86 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
88 * You will write your own definition() method which performs the form set up.
90 * @package moodlecore
91 * @copyright Jamie Pratt <me@jamiep.org>
92 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
94 abstract class moodleform {
95 /** @var string */
96 protected $_formname; // form name
97 /**
98 * quickform object definition
100 * @var MoodleQuickForm MoodleQuickForm
102 protected $_form;
104 * globals workaround
106 * @var array
108 protected $_customdata;
110 * definition_after_data executed flag
111 * @var object definition_finalized
113 protected $_definition_finalized = false;
116 * The constructor function calls the abstract function definition() and it will then
117 * process and clean and attempt to validate incoming data.
119 * It will call your custom validate method to validate data and will also check any rules
120 * you have specified in definition using addRule
122 * The name of the form (id attribute of the form) is automatically generated depending on
123 * the name you gave the class extending moodleform. You should call your class something
124 * like
126 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
127 * current url. If a moodle_url object then outputs params as hidden variables.
128 * @param array $customdata if your form defintion method needs access to data such as $course
129 * $cm, etc. to construct the form definition then pass it in this array. You can
130 * use globals for somethings.
131 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
132 * be merged and used as incoming data to the form.
133 * @param string $target target frame for form submission. You will rarely use this. Don't use
134 * it if you don't need to as the target attribute is deprecated in xhtml
135 * strict.
136 * @param mixed $attributes you can pass a string of html attributes here or an array.
137 * @param bool $editable
138 * @return object moodleform
140 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
141 if (empty($action)){
142 $action = strip_querystring(qualified_me());
145 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
146 $this->_customdata = $customdata;
147 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
148 if (!$editable){
149 $this->_form->hardFreeze();
152 $this->definition();
154 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
155 $this->_form->setType('sesskey', PARAM_RAW);
156 $this->_form->setDefault('sesskey', sesskey());
157 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
158 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
159 $this->_form->setDefault('_qf__'.$this->_formname, 1);
160 $this->_form->_setDefaultRuleMessages();
162 // we have to know all input types before processing submission ;-)
163 $this->_process_submission($method);
167 * To autofocus on first form element or first element with error.
169 * @param string $name if this is set then the focus is forced to a field with this name
171 * @return string javascript to select form element with first error or
172 * first element if no errors. Use this as a parameter
173 * when calling print_header
175 function focus($name=NULL) {
176 $form =& $this->_form;
177 $elkeys = array_keys($form->_elementIndex);
178 $error = false;
179 if (isset($form->_errors) && 0 != count($form->_errors)){
180 $errorkeys = array_keys($form->_errors);
181 $elkeys = array_intersect($elkeys, $errorkeys);
182 $error = true;
185 if ($error or empty($name)) {
186 $names = array();
187 while (empty($names) and !empty($elkeys)) {
188 $el = array_shift($elkeys);
189 $names = $form->_getElNamesRecursive($el);
191 if (!empty($names)) {
192 $name = array_shift($names);
196 $focus = '';
197 if (!empty($name)) {
198 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
201 return $focus;
205 * Internal method. Alters submitted data to be suitable for quickforms processing.
206 * Must be called when the form is fully set up.
208 * @param string $method
210 function _process_submission($method) {
211 $submission = array();
212 if ($method == 'post') {
213 if (!empty($_POST)) {
214 $submission = $_POST;
216 } else {
217 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
220 // following trick is needed to enable proper sesskey checks when using GET forms
221 // the _qf__.$this->_formname serves as a marker that form was actually submitted
222 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
223 if (!confirm_sesskey()) {
224 print_error('invalidsesskey');
226 $files = $_FILES;
227 } else {
228 $submission = array();
229 $files = array();
232 $this->_form->updateSubmission($submission, $files);
236 * Internal method. Validates all old-style deprecated uploaded files.
237 * The new way is to upload files via repository api.
239 * @global object
240 * @global object
241 * @param array $files
242 * @return bool|array Success or an array of errors
244 function _validate_files(&$files) {
245 global $CFG, $COURSE;
247 $files = array();
249 if (empty($_FILES)) {
250 // we do not need to do any checks because no files were submitted
251 // note: server side rules do not work for files - use custom verification in validate() instead
252 return true;
255 $errors = array();
256 $filenames = array();
258 // now check that we really want each file
259 foreach ($_FILES as $elname=>$file) {
260 $required = $this->_form->isElementRequired($elname);
262 if ($file['error'] == 4 and $file['size'] == 0) {
263 if ($required) {
264 $errors[$elname] = get_string('required');
266 unset($_FILES[$elname]);
267 continue;
270 if (!empty($file['error'])) {
271 $errors[$elname] = file_get_upload_error($file['error']);
272 unset($_FILES[$elname]);
273 continue;
276 if (!is_uploaded_file($file['tmp_name'])) {
277 // TODO: improve error message
278 $errors[$elname] = get_string('error');
279 unset($_FILES[$elname]);
280 continue;
283 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
284 // hmm, this file was not requested
285 unset($_FILES[$elname]);
286 continue;
290 // TODO: rethink the file scanning MDL-19380
291 if ($CFG->runclamonupload) {
292 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
293 $errors[$elname] = $_FILES[$elname]['uploadlog'];
294 unset($_FILES[$elname]);
295 continue;
299 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
300 if ($filename === '') {
301 // TODO: improve error message - wrong chars
302 $errors[$elname] = get_string('error');
303 unset($_FILES[$elname]);
304 continue;
306 if (in_array($filename, $filenames)) {
307 // TODO: improve error message - duplicate name
308 $errors[$elname] = get_string('error');
309 unset($_FILES[$elname]);
310 continue;
312 $filenames[] = $filename;
313 $_FILES[$elname]['name'] = $filename;
315 $files[$elname] = $_FILES[$elname]['tmp_name'];
318 // return errors if found
319 if (count($errors) == 0){
320 return true;
322 } else {
323 $files = array();
324 return $errors;
329 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
330 * form definition (new entry form); this function is used to load in data where values
331 * already exist and data is being edited (edit entry form).
333 * note: $slashed param removed
335 * @param mixed $default_values object or array of default values
337 function set_data($default_values) {
338 if (is_object($default_values)) {
339 $default_values = (array)$default_values;
341 $this->_form->setDefaults($default_values);
345 * @deprecated
347 function set_upload_manager($um=false) {
348 debugging('Old file uploads can not be used any more, please use new filepicker element');
352 * Check that form was submitted. Does not check validity of submitted data.
354 * @return bool true if form properly submitted
356 function is_submitted() {
357 return $this->_form->isSubmitted();
361 * @staticvar bool $nosubmit
363 function no_submit_button_pressed(){
364 static $nosubmit = null; // one check is enough
365 if (!is_null($nosubmit)){
366 return $nosubmit;
368 $mform =& $this->_form;
369 $nosubmit = false;
370 if (!$this->is_submitted()){
371 return false;
373 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
374 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
375 $nosubmit = true;
376 break;
379 return $nosubmit;
384 * Check that form data is valid.
385 * You should almost always use this, rather than {@see validate_defined_fields}
387 * @staticvar bool $validated
388 * @return bool true if form data valid
390 function is_validated() {
391 //finalize the form definition before any processing
392 if (!$this->_definition_finalized) {
393 $this->_definition_finalized = true;
394 $this->definition_after_data();
397 return $this->validate_defined_fields();
401 * Validate the form.
403 * You almost always want to call {@see is_validated} instead of this
404 * because it calls {@see definition_after_data} first, before validating the form,
405 * which is what you want in 99% of cases.
407 * This is provided as a separate function for those special cases where
408 * you want the form validated before definition_after_data is called
409 * for example, to selectively add new elements depending on a no_submit_button press,
410 * but only when the form is valid when the no_submit_button is pressed,
412 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
413 * is NOT to validate the form when a no submit button has been pressed.
414 * pass true here to override this behaviour
416 * @return bool true if form data valid
418 function validate_defined_fields($validateonnosubmit=false) {
419 static $validated = null; // one validation is enough
420 $mform =& $this->_form;
421 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
422 return false;
423 } elseif ($validated === null) {
424 $internal_val = $mform->validate();
426 $files = array();
427 $file_val = $this->_validate_files($files);
428 if ($file_val !== true) {
429 if (!empty($file_val)) {
430 foreach ($file_val as $element=>$msg) {
431 $mform->setElementError($element, $msg);
434 $file_val = false;
437 $data = $mform->exportValues();
438 $moodle_val = $this->validation($data, $files);
439 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
440 // non-empty array means errors
441 foreach ($moodle_val as $element=>$msg) {
442 $mform->setElementError($element, $msg);
444 $moodle_val = false;
446 } else {
447 // anything else means validation ok
448 $moodle_val = true;
451 $validated = ($internal_val and $moodle_val and $file_val);
453 return $validated;
457 * Return true if a cancel button has been pressed resulting in the form being submitted.
459 * @return boolean true if a cancel button has been pressed
461 function is_cancelled(){
462 $mform =& $this->_form;
463 if ($mform->isSubmitted()){
464 foreach ($mform->_cancelButtons as $cancelbutton){
465 if (optional_param($cancelbutton, 0, PARAM_RAW)){
466 return true;
470 return false;
474 * Return submitted data if properly submitted or returns NULL if validation fails or
475 * if there is no submitted data.
477 * note: $slashed param removed
479 * @return object submitted data; NULL if not valid or not submitted
481 function get_data() {
482 $mform =& $this->_form;
484 if ($this->is_submitted() and $this->is_validated()) {
485 $data = $mform->exportValues();
486 unset($data['sesskey']); // we do not need to return sesskey
487 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
488 if (empty($data)) {
489 return NULL;
490 } else {
491 return (object)$data;
493 } else {
494 return NULL;
499 * Return submitted data without validation or NULL if there is no submitted data.
500 * note: $slashed param removed
502 * @return object submitted data; NULL if not submitted
504 function get_submitted_data() {
505 $mform =& $this->_form;
507 if ($this->is_submitted()) {
508 $data = $mform->exportValues();
509 unset($data['sesskey']); // we do not need to return sesskey
510 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
511 if (empty($data)) {
512 return NULL;
513 } else {
514 return (object)$data;
516 } else {
517 return NULL;
522 * Save verified uploaded files into directory. Upload process can be customised from definition()
523 * NOTE: please use save_stored_file() or save_file()
525 * @return bool Always false
527 function save_files($destination) {
528 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
529 return false;
533 * Returns name of uploaded file.
535 * @global object
536 * @param string $elname, first element if null
537 * @return mixed false in case of failure, string if ok
539 function get_new_filename($elname=null) {
540 global $USER;
542 if (!$this->is_submitted() or !$this->is_validated()) {
543 return false;
546 if (is_null($elname)) {
547 if (empty($_FILES)) {
548 return false;
550 reset($_FILES);
551 $elname = key($_FILES);
554 if (empty($elname)) {
555 return false;
558 $element = $this->_form->getElement($elname);
560 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
561 $values = $this->_form->exportValues($elname);
562 if (empty($values[$elname])) {
563 return false;
565 $draftid = $values[$elname];
566 $fs = get_file_storage();
567 $context = get_context_instance(CONTEXT_USER, $USER->id);
568 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
569 return false;
571 $file = reset($files);
572 return $file->get_filename();
575 if (!isset($_FILES[$elname])) {
576 return false;
579 return $_FILES[$elname]['name'];
583 * Save file to standard filesystem
585 * @global object
586 * @param string $elname name of element
587 * @param string $pathname full path name of file
588 * @param bool $override override file if exists
589 * @return bool success
591 function save_file($elname, $pathname, $override=false) {
592 global $USER;
594 if (!$this->is_submitted() or !$this->is_validated()) {
595 return false;
597 if (file_exists($pathname)) {
598 if ($override) {
599 if (!@unlink($pathname)) {
600 return false;
602 } else {
603 return false;
607 $element = $this->_form->getElement($elname);
609 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
610 $values = $this->_form->exportValues($elname);
611 if (empty($values[$elname])) {
612 return false;
614 $draftid = $values[$elname];
615 $fs = get_file_storage();
616 $context = get_context_instance(CONTEXT_USER, $USER->id);
617 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
618 return false;
620 $file = reset($files);
622 return $file->copy_content_to($pathname);
624 } else if (isset($_FILES[$elname])) {
625 return copy($_FILES[$elname]['tmp_name'], $pathname);
628 return false;
632 * Returns a temporary file, do not forget to delete after not needed any more.
634 * @param string $elname
635 * @return string or false
637 function save_temp_file($elname) {
638 if (!$this->get_new_filename($elname)) {
639 return false;
641 if (!$dir = make_upload_directory('temp/forms')) {
642 return false;
644 if (!$tempfile = tempnam($dir, 'tempup_')) {
645 return false;
647 if (!$this->save_file($elname, $tempfile, true)) {
648 // something went wrong
649 @unlink($tempfile);
650 return false;
653 return $tempfile;
657 * Get draft files of a form element
658 * This is a protected method which will be used only inside moodleforms
660 * @global object $USER
661 * @param string $elname name of element
662 * @return array
664 protected function get_draft_files($elname) {
665 global $USER;
667 if (!$this->is_submitted()) {
668 return false;
671 $element = $this->_form->getElement($elname);
673 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
674 $values = $this->_form->exportValues($elname);
675 if (empty($values[$elname])) {
676 return false;
678 $draftid = $values[$elname];
679 $fs = get_file_storage();
680 $context = get_context_instance(CONTEXT_USER, $USER->id);
681 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
682 return null;
684 return $files;
686 return null;
690 * Save file to local filesystem pool
692 * @global object
693 * @param string $elname name of element
694 * @param int $newcontextid
695 * @param string $newfilearea
696 * @param string $newfilepath
697 * @param string $newfilename - use specified filename, if not specified name of uploaded file used
698 * @param bool $overwrite - overwrite file if exists
699 * @param int $newuserid - new userid if required
700 * @return mixed stored_file object or false if error; may throw exception if duplicate found
702 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
703 $newfilename=null, $overwrite=false, $newuserid=null) {
704 global $USER;
706 if (!$this->is_submitted() or !$this->is_validated()) {
707 return false;
710 if (empty($newuserid)) {
711 $newuserid = $USER->id;
714 $element = $this->_form->getElement($elname);
715 $fs = get_file_storage();
717 if ($element instanceof MoodleQuickForm_filepicker) {
718 $values = $this->_form->exportValues($elname);
719 if (empty($values[$elname])) {
720 return false;
722 $draftid = $values[$elname];
723 $context = get_context_instance(CONTEXT_USER, $USER->id);
724 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
725 return false;
727 $file = reset($files);
728 if (is_null($newfilename)) {
729 $newfilename = $file->get_filename();
732 if ($overwrite) {
733 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
734 if (!$oldfile->delete()) {
735 return false;
740 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
741 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
742 return $fs->create_file_from_storedfile($file_record, $file);
744 } else if (isset($_FILES[$elname])) {
745 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
747 if ($overwrite) {
748 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
749 if (!$oldfile->delete()) {
750 return false;
755 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
756 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
757 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
760 return false;
764 * Get content of uploaded file.
766 * @global object
767 * @param $element name of file upload element
768 * @return mixed false in case of failure, string if ok
770 function get_file_content($elname) {
771 global $USER;
773 if (!$this->is_submitted() or !$this->is_validated()) {
774 return false;
777 $element = $this->_form->getElement($elname);
779 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
780 $values = $this->_form->exportValues($elname);
781 if (empty($values[$elname])) {
782 return false;
784 $draftid = $values[$elname];
785 $fs = get_file_storage();
786 $context = get_context_instance(CONTEXT_USER, $USER->id);
787 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
788 return false;
790 $file = reset($files);
792 return $file->get_content();
794 } else if (isset($_FILES[$elname])) {
795 return file_get_contents($_FILES[$elname]['tmp_name']);
798 return false;
802 * Print html form.
804 function display() {
805 //finalize the form definition if not yet done
806 if (!$this->_definition_finalized) {
807 $this->_definition_finalized = true;
808 $this->definition_after_data();
810 $this->_form->display();
814 * Abstract method - always override!
816 protected abstract function definition();
819 * Dummy stub method - override if you need to setup the form depending on current
820 * values. This method is called after definition(), data submission and set_data().
821 * All form setup that is dependent on form values should go in here.
823 function definition_after_data(){
827 * Dummy stub method - override if you needed to perform some extra validation.
828 * If there are errors return array of errors ("fieldname"=>"error message"),
829 * otherwise true if ok.
831 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
833 * @param array $data array of ("fieldname"=>value) of submitted data
834 * @param array $files array of uploaded files "element_name"=>tmp_file_path
835 * @return array of "element_name"=>"error_description" if there are errors,
836 * or an empty array if everything is OK (true allowed for backwards compatibility too).
838 function validation($data, $files) {
839 return array();
843 * Method to add a repeating group of elements to a form.
845 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
846 * @param integer $repeats no of times to repeat elements initially
847 * @param array $options Array of options to apply to elements. Array keys are element names.
848 * This is an array of arrays. The second sets of keys are the option types
849 * for the elements :
850 * 'default' - default value is value
851 * 'type' - PARAM_* constant is value
852 * 'helpbutton' - helpbutton params array is value
853 * 'disabledif' - last three moodleform::disabledIf()
854 * params are value as an array
855 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
856 * @param string $addfieldsname name for button to add more fields
857 * @param int $addfieldsno how many fields to add at a time
858 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
859 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
860 * @return int no of repeats of element in this page
862 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
863 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
864 if ($addstring===null){
865 $addstring = get_string('addfields', 'form', $addfieldsno);
866 } else {
867 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
869 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
870 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
871 if (!empty($addfields)){
872 $repeats += $addfieldsno;
874 $mform =& $this->_form;
875 $mform->registerNoSubmitButton($addfieldsname);
876 $mform->addElement('hidden', $repeathiddenname, $repeats);
877 $mform->setType($repeathiddenname, PARAM_INT);
878 //value not to be overridden by submitted value
879 $mform->setConstants(array($repeathiddenname=>$repeats));
880 $namecloned = array();
881 for ($i = 0; $i < $repeats; $i++) {
882 foreach ($elementobjs as $elementobj){
883 $elementclone = fullclone($elementobj);
884 $name = $elementclone->getName();
885 $namecloned[] = $name;
886 if (!empty($name)) {
887 $elementclone->setName($name."[$i]");
889 if (is_a($elementclone, 'HTML_QuickForm_header')) {
890 $value = $elementclone->_text;
891 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
893 } else {
894 $value=$elementclone->getLabel();
895 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
899 $mform->addElement($elementclone);
902 for ($i=0; $i<$repeats; $i++) {
903 foreach ($options as $elementname => $elementoptions){
904 $pos=strpos($elementname, '[');
905 if ($pos!==FALSE){
906 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
907 $realelementname .= substr($elementname, $pos+1);
908 }else {
909 $realelementname = $elementname."[$i]";
911 foreach ($elementoptions as $option => $params){
913 switch ($option){
914 case 'default' :
915 $mform->setDefault($realelementname, $params);
916 break;
917 case 'helpbutton' :
918 $params = array_merge(array($realelementname), $params);
919 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
920 break;
921 case 'disabledif' :
922 foreach ($namecloned as $num => $name){
923 if ($params[0] == $name){
924 $params[0] = $params[0]."[$i]";
925 break;
928 $params = array_merge(array($realelementname), $params);
929 call_user_func_array(array(&$mform, 'disabledIf'), $params);
930 break;
931 case 'rule' :
932 if (is_string($params)){
933 $params = array(null, $params, null, 'client');
935 $params = array_merge(array($realelementname), $params);
936 call_user_func_array(array(&$mform, 'addRule'), $params);
937 break;
943 $mform->addElement('submit', $addfieldsname, $addstring);
945 if (!$addbuttoninside) {
946 $mform->closeHeaderBefore($addfieldsname);
949 return $repeats;
953 * Adds a link/button that controls the checked state of a group of checkboxes.
955 * @global object
956 * @param int $groupid The id of the group of advcheckboxes this element controls
957 * @param string $buttontext The text of the link. Defaults to "select all/none"
958 * @param array $attributes associative array of HTML attributes
959 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
961 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
962 global $CFG;
963 if (empty($text)) {
964 $text = get_string('selectallornone', 'form');
967 $mform = $this->_form;
968 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
970 if ($select_value == 0 || is_null($select_value)) {
971 $new_select_value = 1;
972 } else {
973 $new_select_value = 0;
976 $mform->addElement('hidden', "checkbox_controller$groupid");
977 $mform->setType("checkbox_controller$groupid", PARAM_INT);
978 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
980 // Locate all checkboxes for this group and set their value, IF the optional param was given
981 if (!is_null($select_value)) {
982 foreach ($this->_form->_elements as $element) {
983 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
984 $mform->setConstants(array($element->getAttribute('name') => $select_value));
989 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
990 $mform->registerNoSubmitButton($checkbox_controller_name);
992 // Prepare Javascript for submit element
993 $js = "\n//<![CDATA[\n";
994 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
995 $js .= <<<EOS
996 function html_quickform_toggle_checkboxes(group) {
997 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
998 var newvalue = false;
999 var global = eval('html_quickform_checkboxgroup' + group + ';');
1000 if (global == 1) {
1001 eval('html_quickform_checkboxgroup' + group + ' = 0;');
1002 newvalue = '';
1003 } else {
1004 eval('html_quickform_checkboxgroup' + group + ' = 1;');
1005 newvalue = 'checked';
1008 for (i = 0; i < checkboxes.length; i++) {
1009 checkboxes[i].checked = newvalue;
1012 EOS;
1013 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
1015 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
1017 $js .= "//]]>\n";
1019 require_once("$CFG->libdir/form/submitlink.php");
1020 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
1021 $submitlink->_js = $js;
1022 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
1023 $mform->addElement($submitlink);
1024 $mform->setDefault($checkbox_controller_name, $text);
1028 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1029 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1030 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1031 * get data with get_data().
1033 * @param boolean $cancel whether to show cancel button, default true
1034 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1036 function add_action_buttons($cancel = true, $submitlabel=null){
1037 if (is_null($submitlabel)){
1038 $submitlabel = get_string('savechanges');
1040 $mform =& $this->_form;
1041 if ($cancel){
1042 //when two elements we need a group
1043 $buttonarray=array();
1044 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1045 $buttonarray[] = &$mform->createElement('cancel');
1046 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1047 $mform->closeHeaderBefore('buttonar');
1048 } else {
1049 //no group needed
1050 $mform->addElement('submit', 'submitbutton', $submitlabel);
1051 $mform->closeHeaderBefore('submitbutton');
1056 * Adds an initialisation call for a standard JavaScript enhancement.
1058 * This function is designed to add an initialisation call for a JavaScript
1059 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1061 * Current options:
1062 * - Selectboxes
1063 * - smartselect: Turns a nbsp indented select box into a custom drop down
1064 * control that supports multilevel and category selection.
1065 * $enhancement = 'smartselect';
1066 * $options = array('selectablecategories' => true|false)
1068 * @since 2.0
1069 * @param string|element $element
1070 * @param string $enhancement
1071 * @param array $options
1072 * @param array $strings
1074 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1075 global $PAGE;
1076 if (is_string($element)) {
1077 $element = $this->_form->getElement($element);
1079 if (is_object($element)) {
1080 $element->_generateId();
1081 $elementid = $element->getAttribute('id');
1082 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1083 if (is_array($strings)) {
1084 foreach ($strings as $string) {
1085 if (is_array($string)) {
1086 call_user_method_array('string_for_js', $PAGE->requires, $string);
1087 } else {
1088 $PAGE->requires->string_for_js($string, 'moodle');
1096 * Returns a JS module definition for the mforms JS
1097 * @return array
1099 public static function get_js_module() {
1100 global $CFG;
1101 return array(
1102 'name' => 'mform',
1103 'fullpath' => '/lib/form/form.js',
1104 'requires' => array('base', 'node'),
1105 'strings' => array(
1106 array('showadvanced', 'form'),
1107 array('hideadvanced', 'form')
1114 * You never extend this class directly. The class methods of this class are available from
1115 * the private $this->_form property on moodleform and its children. You generally only
1116 * call methods on this class from within abstract methods that you override on moodleform such
1117 * as definition and definition_after_data
1119 * @package moodlecore
1120 * @copyright Jamie Pratt <me@jamiep.org>
1121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1123 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1124 /** @var array */
1125 var $_types = array();
1126 var $_dependencies = array();
1128 * Array of buttons that if pressed do not result in the processing of the form.
1130 * @var array
1132 var $_noSubmitButtons=array();
1134 * Array of buttons that if pressed do not result in the processing of the form.
1136 * @var array
1138 var $_cancelButtons=array();
1141 * Array whose keys are element names. If the key exists this is a advanced element
1143 * @var array
1145 var $_advancedElements = array();
1148 * Whether to display advanced elements (on page load)
1150 * @var boolean
1152 var $_showAdvanced = null;
1155 * The form name is derived from the class name of the wrapper minus the trailing form
1156 * It is a name with words joined by underscores whereas the id attribute is words joined by
1157 * underscores.
1159 * @var unknown_type
1161 var $_formName = '';
1164 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1166 * @var string
1168 var $_pageparams = '';
1171 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1173 * @global object
1174 * @staticvar int $formcounter
1175 * @param string $formName Form's name.
1176 * @param string $method (optional)Form's method defaults to 'POST'
1177 * @param mixed $action (optional)Form's action - string or moodle_url
1178 * @param string $target (optional)Form's target defaults to none
1179 * @param mixed $attributes (optional)Extra attributes for <form> tag
1180 * @access public
1182 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1183 global $CFG, $OUTPUT;
1185 static $formcounter = 1;
1187 HTML_Common::HTML_Common($attributes);
1188 $target = empty($target) ? array() : array('target' => $target);
1189 $this->_formName = $formName;
1190 if (is_a($action, 'moodle_url')){
1191 $this->_pageparams = html_writer::input_hidden_params($action);
1192 $action = $action->out_omit_querystring();
1193 } else {
1194 $this->_pageparams = '';
1196 //no 'name' atttribute for form in xhtml strict :
1197 $attributes = array('action'=>$action, 'method'=>$method,
1198 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1199 $formcounter++;
1200 $this->updateAttributes($attributes);
1202 //this is custom stuff for Moodle :
1203 $oldclass= $this->getAttribute('class');
1204 if (!empty($oldclass)){
1205 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1206 }else {
1207 $this->updateAttributes(array('class'=>'mform'));
1209 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1210 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1211 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1215 * Use this method to indicate an element in a form is an advanced field. If items in a form
1216 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1217 * form so the user can decide whether to display advanced form controls.
1219 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1221 * @param string $elementName group or element name (not the element name of something inside a group).
1222 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1224 function setAdvanced($elementName, $advanced=true){
1225 if ($advanced){
1226 $this->_advancedElements[$elementName]='';
1227 } elseif (isset($this->_advancedElements[$elementName])) {
1228 unset($this->_advancedElements[$elementName]);
1230 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1231 $this->setShowAdvanced();
1232 $this->registerNoSubmitButton('mform_showadvanced');
1234 $this->addElement('hidden', 'mform_showadvanced_last');
1235 $this->setType('mform_showadvanced_last', PARAM_INT);
1239 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1240 * display advanced elements in the form until 'Show Advanced' is pressed.
1242 * You can get the last state of the form and possibly save it for this user by using
1243 * value 'mform_showadvanced_last' in submitted data.
1245 * @param boolean $showadvancedNow
1247 function setShowAdvanced($showadvancedNow = null){
1248 if ($showadvancedNow === null){
1249 if ($this->_showAdvanced !== null){
1250 return;
1251 } else { //if setShowAdvanced is called without any preference
1252 //make the default to not show advanced elements.
1253 $showadvancedNow = get_user_preferences(
1254 moodle_strtolower($this->_formName.'_showadvanced', 0));
1257 //value of hidden element
1258 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1259 //value of button
1260 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1261 //toggle if button pressed or else stay the same
1262 if ($hiddenLast == -1) {
1263 $next = $showadvancedNow;
1264 } elseif ($buttonPressed) { //toggle on button press
1265 $next = !$hiddenLast;
1266 } else {
1267 $next = $hiddenLast;
1269 $this->_showAdvanced = $next;
1270 if ($showadvancedNow != $next){
1271 set_user_preference($this->_formName.'_showadvanced', $next);
1273 $this->setConstants(array('mform_showadvanced_last'=>$next));
1275 function getShowAdvanced(){
1276 return $this->_showAdvanced;
1281 * Accepts a renderer
1283 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
1284 * @access public
1285 * @return void
1287 function accept(&$renderer) {
1288 if (method_exists($renderer, 'setAdvancedElements')){
1289 //check for visible fieldsets where all elements are advanced
1290 //and mark these headers as advanced as well.
1291 //And mark all elements in a advanced header as advanced
1292 $stopFields = $renderer->getStopFieldSetElements();
1293 $lastHeader = null;
1294 $lastHeaderAdvanced = false;
1295 $anyAdvanced = false;
1296 foreach (array_keys($this->_elements) as $elementIndex){
1297 $element =& $this->_elements[$elementIndex];
1299 // if closing header and any contained element was advanced then mark it as advanced
1300 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1301 if ($anyAdvanced && !is_null($lastHeader)){
1302 $this->setAdvanced($lastHeader->getName());
1304 $lastHeaderAdvanced = false;
1305 unset($lastHeader);
1306 $lastHeader = null;
1307 } elseif ($lastHeaderAdvanced) {
1308 $this->setAdvanced($element->getName());
1311 if ($element->getType()=='header'){
1312 $lastHeader =& $element;
1313 $anyAdvanced = false;
1314 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1315 } elseif (isset($this->_advancedElements[$element->getName()])){
1316 $anyAdvanced = true;
1319 // the last header may not be closed yet...
1320 if ($anyAdvanced && !is_null($lastHeader)){
1321 $this->setAdvanced($lastHeader->getName());
1323 $renderer->setAdvancedElements($this->_advancedElements);
1326 parent::accept($renderer);
1330 * @param string $elementName
1332 function closeHeaderBefore($elementName){
1333 $renderer =& $this->defaultRenderer();
1334 $renderer->addStopFieldsetElements($elementName);
1338 * Should be used for all elements of a form except for select, radio and checkboxes which
1339 * clean their own data.
1341 * @param string $elementname
1342 * @param integer $paramtype use the constants PARAM_*.
1343 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1344 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1345 * It will strip all html tags. But will still let tags for multilang support
1346 * through.
1347 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1348 * html editor. Data from the editor is later cleaned before display using
1349 * format_text() function. PARAM_RAW can also be used for data that is validated
1350 * by some other way or printed by p() or s().
1351 * * PARAM_INT should be used for integers.
1352 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1353 * form actions.
1355 function setType($elementname, $paramtype) {
1356 $this->_types[$elementname] = $paramtype;
1360 * See description of setType above. This can be used to set several types at once.
1362 * @param array $paramtypes
1364 function setTypes($paramtypes) {
1365 $this->_types = $paramtypes + $this->_types;
1369 * @param array $submission
1370 * @param array $files
1372 function updateSubmission($submission, $files) {
1373 $this->_flagSubmitted = false;
1375 if (empty($submission)) {
1376 $this->_submitValues = array();
1377 } else {
1378 foreach ($submission as $key=>$s) {
1379 if (array_key_exists($key, $this->_types)) {
1380 $submission[$key] = clean_param($s, $this->_types[$key]);
1383 $this->_submitValues = $submission;
1384 $this->_flagSubmitted = true;
1387 if (empty($files)) {
1388 $this->_submitFiles = array();
1389 } else {
1390 $this->_submitFiles = $files;
1391 $this->_flagSubmitted = true;
1394 // need to tell all elements that they need to update their value attribute.
1395 foreach (array_keys($this->_elements) as $key) {
1396 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1401 * @return string
1403 function getReqHTML(){
1404 return $this->_reqHTML;
1408 * @return string
1410 function getAdvancedHTML(){
1411 return $this->_advancedHTML;
1415 * Initializes a default form value. Used to specify the default for a new entry where
1416 * no data is loaded in using moodleform::set_data()
1418 * note: $slashed param removed
1420 * @param string $elementname element name
1421 * @param mixed $values values for that element name
1422 * @access public
1423 * @return void
1425 function setDefault($elementName, $defaultValue){
1426 $this->setDefaults(array($elementName=>$defaultValue));
1427 } // end func setDefault
1429 * Add an array of buttons to the form
1430 * @param array $buttons An associative array representing help button to attach to
1431 * to the form. keys of array correspond to names of elements in form.
1432 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1433 * @param bool $suppresscheck
1434 * @param string $function
1435 * @access public
1437 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1439 debugging('function moodle_form::setHelpButtons() is deprecated');
1440 //foreach ($buttons as $elementname => $button){
1441 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1445 * Add a single button.
1447 * @deprecated use addHelpButton() instead
1448 * @param string $elementname name of the element to add the item to
1449 * @param array $button arguments to pass to function $function
1450 * @param boolean $suppresscheck whether to throw an error if the element
1451 * doesn't exist.
1452 * @param string $function - function to generate html from the arguments in $button
1453 * @param string $function
1455 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1456 global $OUTPUT;
1458 debugging('function moodle_form::setHelpButton() is deprecated');
1459 if ($function !== 'helpbutton') {
1460 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1463 $buttonargs = (array)$buttonargs;
1465 if (array_key_exists($elementname, $this->_elementIndex)) {
1466 //_elements has a numeric index, this code accesses the elements by name
1467 $element = $this->_elements[$this->_elementIndex[$elementname]];
1469 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1470 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1471 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1472 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1474 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1476 } else if (!$suppresscheck) {
1477 print_error('nonexistentformelements', 'form', '', $elementname);
1482 * Add a help button to element, only one button per element is allowed.
1484 * This is new, simplified and preferable method of setting a help icon on form elements.
1485 * It uses the new $OUTPUT->help_icon().
1487 * Typically, you will provide the same identifier and the component as you have used for the
1488 * label of the element. The string identifier with the _help suffix added is then used
1489 * as the help string.
1491 * There has to be two strings defined:
1492 * 1/ get_string($identifier, $component) - the title of the help page
1493 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1495 * @since 2.0
1496 * @param string $elementname name of the element to add the item to
1497 * @param string $identifier help string identifier without _help suffix
1498 * @param string $component component name to look the help string in
1499 * @param string $linktext optional text to display next to the icon
1500 * @param boolean $suppresscheck set to true if the element may not exist
1501 * @return void
1503 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1504 global $OUTPUT;
1505 if (array_key_exists($elementname, $this->_elementIndex)) {
1506 $element = $this->_elements[$this->_elementIndex[$elementname]];
1507 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1508 } else if (!$suppresscheck) {
1509 debugging(get_string('nonexistentformelements', 'form', $elementname));
1514 * Set constant value not overridden by _POST or _GET
1515 * note: this does not work for complex names with [] :-(
1517 * @param string $elname name of element
1518 * @param mixed $value
1519 * @return void
1521 function setConstant($elname, $value) {
1522 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1523 $element =& $this->getElement($elname);
1524 $element->onQuickFormEvent('updateValue', null, $this);
1528 * @param string $elementList
1530 function exportValues($elementList = null){
1531 $unfiltered = array();
1532 if (null === $elementList) {
1533 // iterate over all elements, calling their exportValue() methods
1534 $emptyarray = array();
1535 foreach (array_keys($this->_elements) as $key) {
1536 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1537 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1538 } else {
1539 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1542 if (is_array($value)) {
1543 // This shit throws a bogus warning in PHP 4.3.x
1544 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1547 } else {
1548 if (!is_array($elementList)) {
1549 $elementList = array_map('trim', explode(',', $elementList));
1551 foreach ($elementList as $elementName) {
1552 $value = $this->exportValue($elementName);
1553 if (PEAR::isError($value)) {
1554 return $value;
1556 //oh, stock QuickFOrm was returning array of arrays!
1557 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1561 return $unfiltered;
1564 * Adds a validation rule for the given field
1566 * If the element is in fact a group, it will be considered as a whole.
1567 * To validate grouped elements as separated entities,
1568 * use addGroupRule instead of addRule.
1570 * @param string $element Form element name
1571 * @param string $message Message to display for invalid data
1572 * @param string $type Rule type, use getRegisteredRules() to get types
1573 * @param string $format (optional)Required for extra rule data
1574 * @param string $validation (optional)Where to perform validation: "server", "client"
1575 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1576 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1577 * @access public
1579 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1581 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1582 if ($validation == 'client') {
1583 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1586 } // end func addRule
1588 * Adds a validation rule for the given group of elements
1590 * Only groups with a name can be assigned a validation rule
1591 * Use addGroupRule when you need to validate elements inside the group.
1592 * Use addRule if you need to validate the group as a whole. In this case,
1593 * the same rule will be applied to all elements in the group.
1594 * Use addRule if you need to validate the group against a function.
1596 * @param string $group Form group name
1597 * @param mixed $arg1 Array for multiple elements or error message string for one element
1598 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1599 * @param string $format (optional)Required for extra rule data
1600 * @param int $howmany (optional)How many valid elements should be in the group
1601 * @param string $validation (optional)Where to perform validation: "server", "client"
1602 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1603 * @access public
1605 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1607 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1608 if (is_array($arg1)) {
1609 foreach ($arg1 as $rules) {
1610 foreach ($rules as $rule) {
1611 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1613 if ('client' == $validation) {
1614 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1618 } elseif (is_string($arg1)) {
1620 if ($validation == 'client') {
1621 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1624 } // end func addGroupRule
1626 // }}}
1628 * Returns the client side validation script
1630 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1631 * and slightly modified to run rules per-element
1632 * Needed to override this because of an error with client side validation of grouped elements.
1634 * @access public
1635 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1637 function getValidationScript()
1639 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1640 return '';
1643 include_once('HTML/QuickForm/RuleRegistry.php');
1644 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1645 $test = array();
1646 $js_escape = array(
1647 "\r" => '\r',
1648 "\n" => '\n',
1649 "\t" => '\t',
1650 "'" => "\\'",
1651 '"' => '\"',
1652 '\\' => '\\\\'
1655 foreach ($this->_rules as $elementName => $rules) {
1656 foreach ($rules as $rule) {
1657 if ('client' == $rule['validation']) {
1658 unset($element); //TODO: find out how to properly initialize it
1660 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1661 $rule['message'] = strtr($rule['message'], $js_escape);
1663 if (isset($rule['group'])) {
1664 $group =& $this->getElement($rule['group']);
1665 // No JavaScript validation for frozen elements
1666 if ($group->isFrozen()) {
1667 continue 2;
1669 $elements =& $group->getElements();
1670 foreach (array_keys($elements) as $key) {
1671 if ($elementName == $group->getElementName($key)) {
1672 $element =& $elements[$key];
1673 break;
1676 } elseif ($dependent) {
1677 $element = array();
1678 $element[] =& $this->getElement($elementName);
1679 foreach ($rule['dependent'] as $elName) {
1680 $element[] =& $this->getElement($elName);
1682 } else {
1683 $element =& $this->getElement($elementName);
1685 // No JavaScript validation for frozen elements
1686 if (is_object($element) && $element->isFrozen()) {
1687 continue 2;
1688 } elseif (is_array($element)) {
1689 foreach (array_keys($element) as $key) {
1690 if ($element[$key]->isFrozen()) {
1691 continue 3;
1695 // Fix for bug displaying errors for elements in a group
1696 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1697 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1698 $test[$elementName][1]=$element;
1699 //end of fix
1704 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1705 // the form, and then that form field gets corrupted by the code that follows.
1706 unset($element);
1708 $js = '
1709 <script type="text/javascript">
1710 //<![CDATA[
1712 var skipClientValidation = false;
1714 function qf_errorHandler(element, _qfMsg) {
1715 div = element.parentNode;
1716 if (_qfMsg != \'\') {
1717 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1718 if (!errorSpan) {
1719 errorSpan = document.createElement("span");
1720 errorSpan.id = \'id_error_\'+element.name;
1721 errorSpan.className = "error";
1722 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1725 while (errorSpan.firstChild) {
1726 errorSpan.removeChild(errorSpan.firstChild);
1729 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1730 errorSpan.appendChild(document.createElement("br"));
1732 if (div.className.substr(div.className.length - 6, 6) != " error"
1733 && div.className != "error") {
1734 div.className += " error";
1737 return false;
1738 } else {
1739 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1740 if (errorSpan) {
1741 errorSpan.parentNode.removeChild(errorSpan);
1744 if (div.className.substr(div.className.length - 6, 6) == " error") {
1745 div.className = div.className.substr(0, div.className.length - 6);
1746 } else if (div.className == "error") {
1747 div.className = "";
1750 return true;
1753 $validateJS = '';
1754 foreach ($test as $elementName => $jsandelement) {
1755 // Fix for bug displaying errors for elements in a group
1756 //unset($element);
1757 list($jsArr,$element)=$jsandelement;
1758 //end of fix
1759 $escapedElementName = preg_replace_callback(
1760 '/[_\[\]]/',
1761 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1762 $elementName);
1763 $js .= '
1764 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1765 var value = \'\';
1766 var errFlag = new Array();
1767 var _qfGroups = {};
1768 var _qfMsg = \'\';
1769 var frm = element.parentNode;
1770 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1771 frm = frm.parentNode;
1773 ' . join("\n", $jsArr) . '
1774 return qf_errorHandler(element, _qfMsg);
1777 $validateJS .= '
1778 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1779 if (!ret && !first_focus) {
1780 first_focus = true;
1781 frm.elements[\''.$elementName.'\'].focus();
1785 // Fix for bug displaying errors for elements in a group
1786 //unset($element);
1787 //$element =& $this->getElement($elementName);
1788 //end of fix
1789 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1790 $onBlur = $element->getAttribute('onBlur');
1791 $onChange = $element->getAttribute('onChange');
1792 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1793 'onChange' => $onChange . $valFunc));
1795 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1796 $js .= '
1797 function validate_' . $this->_formName . '(frm) {
1798 if (skipClientValidation) {
1799 return true;
1801 var ret = true;
1803 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1804 var first_focus = false;
1805 ' . $validateJS . ';
1806 return ret;
1808 //]]>
1809 </script>';
1810 return $js;
1811 } // end func getValidationScript
1812 function _setDefaultRuleMessages(){
1813 foreach ($this->_rules as $field => $rulesarr){
1814 foreach ($rulesarr as $key => $rule){
1815 if ($rule['message']===null){
1816 $a=new stdClass();
1817 $a->format=$rule['format'];
1818 $str=get_string('err_'.$rule['type'], 'form', $a);
1819 if (strpos($str, '[[')!==0){
1820 $this->_rules[$field][$key]['message']=$str;
1827 function getLockOptionObject(){
1828 $result = array();
1829 foreach ($this->_dependencies as $dependentOn => $conditions){
1830 $result[$dependentOn] = array();
1831 foreach ($conditions as $condition=>$values) {
1832 $result[$dependentOn][$condition] = array();
1833 foreach ($values as $value=>$dependents) {
1834 $result[$dependentOn][$condition][$value] = array();
1835 $i = 0;
1836 foreach ($dependents as $dependent) {
1837 $elements = $this->_getElNamesRecursive($dependent);
1838 if (empty($elements)) {
1839 // probably element inside of some group
1840 $elements = array($dependent);
1842 foreach($elements as $element) {
1843 if ($element == $dependentOn) {
1844 continue;
1846 $result[$dependentOn][$condition][$value][] = $element;
1852 return array($this->getAttribute('id'), $result);
1856 * @param mixed $element
1857 * @return array
1859 function _getElNamesRecursive($element) {
1860 if (is_string($element)) {
1861 if (!$this->elementExists($element)) {
1862 return array();
1864 $element = $this->getElement($element);
1867 if (is_a($element, 'HTML_QuickForm_group')) {
1868 $elsInGroup = $element->getElements();
1869 $elNames = array();
1870 foreach ($elsInGroup as $elInGroup){
1871 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1872 // not sure if this would work - groups nested in groups
1873 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1874 } else {
1875 $elNames[] = $element->getElementName($elInGroup->getName());
1879 } else if (is_a($element, 'HTML_QuickForm_header')) {
1880 return array();
1882 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1883 return array();
1885 } else if (method_exists($element, 'getPrivateName')) {
1886 return array($element->getPrivateName());
1888 } else {
1889 $elNames = array($element->getName());
1892 return $elNames;
1896 * Adds a dependency for $elementName which will be disabled if $condition is met.
1897 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1898 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1899 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1900 * of the $dependentOn element is $condition (such as equal) to $value.
1902 * @param string $elementName the name of the element which will be disabled
1903 * @param string $dependentOn the name of the element whose state will be checked for
1904 * condition
1905 * @param string $condition the condition to check
1906 * @param mixed $value used in conjunction with condition.
1908 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1909 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1910 $this->_dependencies[$dependentOn] = array();
1912 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1913 $this->_dependencies[$dependentOn][$condition] = array();
1915 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1916 $this->_dependencies[$dependentOn][$condition][$value] = array();
1918 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1921 function registerNoSubmitButton($buttonname){
1922 $this->_noSubmitButtons[]=$buttonname;
1926 * @param string $buttonname
1927 * @return mixed
1929 function isNoSubmitButton($buttonname){
1930 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1934 * @param string $buttonname
1936 function _registerCancelButton($addfieldsname){
1937 $this->_cancelButtons[]=$addfieldsname;
1940 * Displays elements without HTML input tags.
1941 * This method is different to freeze() in that it makes sure no hidden
1942 * elements are included in the form.
1943 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1945 * This function also removes all previously defined rules.
1947 * @param mixed $elementList array or string of element(s) to be frozen
1948 * @access public
1950 function hardFreeze($elementList=null)
1952 if (!isset($elementList)) {
1953 $this->_freezeAll = true;
1954 $elementList = array();
1955 } else {
1956 if (!is_array($elementList)) {
1957 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1959 $elementList = array_flip($elementList);
1962 foreach (array_keys($this->_elements) as $key) {
1963 $name = $this->_elements[$key]->getName();
1964 if ($this->_freezeAll || isset($elementList[$name])) {
1965 $this->_elements[$key]->freeze();
1966 $this->_elements[$key]->setPersistantFreeze(false);
1967 unset($elementList[$name]);
1969 // remove all rules
1970 $this->_rules[$name] = array();
1971 // if field is required, remove the rule
1972 $unset = array_search($name, $this->_required);
1973 if ($unset !== false) {
1974 unset($this->_required[$unset]);
1979 if (!empty($elementList)) {
1980 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);
1982 return true;
1985 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1987 * This function also removes all previously defined rules of elements it freezes.
1989 * throws HTML_QuickForm_Error
1991 * @param array $elementList array or string of element(s) not to be frozen
1992 * @access public
1994 function hardFreezeAllVisibleExcept($elementList)
1996 $elementList = array_flip($elementList);
1997 foreach (array_keys($this->_elements) as $key) {
1998 $name = $this->_elements[$key]->getName();
1999 $type = $this->_elements[$key]->getType();
2001 if ($type == 'hidden'){
2002 // leave hidden types as they are
2003 } elseif (!isset($elementList[$name])) {
2004 $this->_elements[$key]->freeze();
2005 $this->_elements[$key]->setPersistantFreeze(false);
2007 // remove all rules
2008 $this->_rules[$name] = array();
2009 // if field is required, remove the rule
2010 $unset = array_search($name, $this->_required);
2011 if ($unset !== false) {
2012 unset($this->_required[$unset]);
2016 return true;
2019 * Tells whether the form was already submitted
2021 * This is useful since the _submitFiles and _submitValues arrays
2022 * may be completely empty after the trackSubmit value is removed.
2024 * @access public
2025 * @return bool
2027 function isSubmitted()
2029 return parent::isSubmitted() && (!$this->isFrozen());
2035 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2036 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2038 * Stylesheet is part of standard theme and should be automatically included.
2040 * @package moodlecore
2041 * @copyright Jamie Pratt <me@jamiep.org>
2042 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2044 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2047 * Element template array
2048 * @var array
2049 * @access private
2051 var $_elementTemplates;
2053 * Template used when opening a hidden fieldset
2054 * (i.e. a fieldset that is opened when there is no header element)
2055 * @var string
2056 * @access private
2058 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2060 * Header Template string
2061 * @var string
2062 * @access private
2064 var $_headerTemplate =
2065 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2068 * Template used when opening a fieldset
2069 * @var string
2070 * @access private
2072 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2075 * Template used when closing a fieldset
2076 * @var string
2077 * @access private
2079 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2082 * Required Note template string
2083 * @var string
2084 * @access private
2086 var $_requiredNoteTemplate =
2087 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2089 var $_advancedElements = array();
2092 * Whether to display advanced elements (on page load)
2094 * @var integer 1 means show 0 means hide
2096 var $_showAdvanced;
2098 function MoodleQuickForm_Renderer(){
2099 // switch next two lines for ol li containers for form items.
2100 // $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>');
2101 $this->_elementTemplates = array(
2102 '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>',
2104 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2106 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}&nbsp;</div></div>',
2108 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2110 'nodisplay'=>'');
2112 parent::HTML_QuickForm_Renderer_Tableless();
2116 * @param array $elements
2118 function setAdvancedElements($elements){
2119 $this->_advancedElements = $elements;
2123 * What to do when starting the form
2125 * @param object $form MoodleQuickForm
2127 function startForm(&$form){
2128 $this->_reqHTML = $form->getReqHTML();
2129 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2130 $this->_advancedHTML = $form->getAdvancedHTML();
2131 $this->_showAdvanced = $form->getShowAdvanced();
2132 parent::startForm($form);
2133 if ($form->isFrozen()){
2134 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2135 } else {
2136 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2137 $this->_hiddenHtml .= $form->_pageparams;
2144 * @param object $group Passed by reference
2145 * @param mixed $required
2146 * @param mixed $error
2148 function startGroup(&$group, $required, $error){
2149 if (method_exists($group, 'getElementTemplateType')){
2150 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2151 }else{
2152 $html = $this->_elementTemplates['default'];
2155 if ($this->_showAdvanced){
2156 $advclass = ' advanced';
2157 } else {
2158 $advclass = ' advanced hide';
2160 if (isset($this->_advancedElements[$group->getName()])){
2161 $html =str_replace(' {advanced}', $advclass, $html);
2162 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2163 } else {
2164 $html =str_replace(' {advanced}', '', $html);
2165 $html =str_replace('{advancedimg}', '', $html);
2167 if (method_exists($group, 'getHelpButton')){
2168 $html =str_replace('{help}', $group->getHelpButton(), $html);
2169 }else{
2170 $html =str_replace('{help}', '', $html);
2172 $html =str_replace('{name}', $group->getName(), $html);
2173 $html =str_replace('{type}', 'fgroup', $html);
2175 $this->_templates[$group->getName()]=$html;
2176 // Fix for bug in tableless quickforms that didn't allow you to stop a
2177 // fieldset before a group of elements.
2178 // if the element name indicates the end of a fieldset, close the fieldset
2179 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2180 && $this->_fieldsetsOpen > 0
2182 $this->_html .= $this->_closeFieldsetTemplate;
2183 $this->_fieldsetsOpen--;
2185 parent::startGroup($group, $required, $error);
2188 * @param object $element
2189 * @param mixed $required
2190 * @param mixed $error
2192 function renderElement(&$element, $required, $error){
2193 //manipulate id of all elements before rendering
2194 if (!is_null($element->getAttribute('id'))) {
2195 $id = $element->getAttribute('id');
2196 } else {
2197 $id = $element->getName();
2199 //strip qf_ prefix and replace '[' with '_' and strip ']'
2200 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
2201 if (strpos($id, 'id_') !== 0){
2202 $element->updateAttributes(array('id'=>'id_'.$id));
2205 //adding stuff to place holders in template
2206 //check if this is a group element first
2207 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2208 // so it gets substitutions for *each* element
2209 $html = $this->_groupElementTemplate;
2211 elseif (method_exists($element, 'getElementTemplateType')){
2212 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2213 }else{
2214 $html = $this->_elementTemplates['default'];
2216 if ($this->_showAdvanced){
2217 $advclass = ' advanced';
2218 } else {
2219 $advclass = ' advanced hide';
2221 if (isset($this->_advancedElements[$element->getName()])){
2222 $html =str_replace(' {advanced}', $advclass, $html);
2223 } else {
2224 $html =str_replace(' {advanced}', '', $html);
2226 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2227 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2228 } else {
2229 $html =str_replace('{advancedimg}', '', $html);
2231 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2232 $html =str_replace('{name}', $element->getName(), $html);
2233 if (method_exists($element, 'getHelpButton')){
2234 $html = str_replace('{help}', $element->getHelpButton(), $html);
2235 }else{
2236 $html = str_replace('{help}', '', $html);
2239 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2240 $this->_groupElementTemplate = $html;
2242 elseif (!isset($this->_templates[$element->getName()])) {
2243 $this->_templates[$element->getName()] = $html;
2246 parent::renderElement($element, $required, $error);
2250 * @global moodle_page $PAGE
2251 * @param object $form Passed by reference
2253 function finishForm(&$form){
2254 global $PAGE;
2255 if ($form->isFrozen()){
2256 $this->_hiddenHtml = '';
2258 parent::finishForm($form);
2259 if (!$form->isFrozen()) {
2260 $args = $form->getLockOptionObject();
2261 if (count($args[1]) > 0) {
2262 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, false, moodleform::get_js_module());
2267 * Called when visiting a header element
2269 * @param object $header An HTML_QuickForm_header element being visited
2270 * @access public
2271 * @return void
2272 * @global moodle_page $PAGE
2274 function renderHeader(&$header) {
2275 global $PAGE;
2277 $name = $header->getName();
2279 $id = empty($name) ? '' : ' id="' . $name . '"';
2280 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2281 if (is_null($header->_text)) {
2282 $header_html = '';
2283 } elseif (!empty($name) && isset($this->_templates[$name])) {
2284 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2285 } else {
2286 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2289 if (isset($this->_advancedElements[$name])){
2290 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2291 $elementName='mform_showadvanced';
2292 if ($this->_showAdvanced==0){
2293 $buttonlabel = get_string('showadvanced', 'form');
2294 } else {
2295 $buttonlabel = get_string('hideadvanced', 'form');
2297 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2298 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2299 $header_html = str_replace('{button}', $button, $header_html);
2300 } else {
2301 $header_html =str_replace('{advancedimg}', '', $header_html);
2302 $header_html = str_replace('{button}', '', $header_html);
2305 if ($this->_fieldsetsOpen > 0) {
2306 $this->_html .= $this->_closeFieldsetTemplate;
2307 $this->_fieldsetsOpen--;
2310 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2311 if ($this->_showAdvanced){
2312 $advclass = ' class="advanced"';
2313 } else {
2314 $advclass = ' class="advanced hide"';
2316 if (isset($this->_advancedElements[$name])){
2317 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2318 } else {
2319 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2321 $this->_html .= $openFieldsetTemplate . $header_html;
2322 $this->_fieldsetsOpen++;
2323 } // end func renderHeader
2325 function getStopFieldsetElements(){
2326 return $this->_stopFieldsetElements;
2331 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2332 * @name $_HTML_QuickForm_default_renderer
2334 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2336 /** Please keep this list in alphabetical order. */
2337 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2338 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2339 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2340 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2341 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2342 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2343 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2344 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2345 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2346 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2347 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2348 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2349 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2350 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2351 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2352 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2353 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2354 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2355 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2356 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2357 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2358 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2359 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2360 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2361 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2362 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2363 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2364 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2365 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2366 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2367 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2368 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2369 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2370 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2371 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2372 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');