MDL-20636 fix most of the remaining codechecker issues in mod/quiz and lib/questionli...
[moodle.git] / lib / formslib.php
blob91e49bd1f7a5c9e21c0faafa44c73d69af881dda
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 or cancelled
481 function get_data() {
482 $mform =& $this->_form;
484 if (!$this->is_cancelled() and $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 $text The text of the link. Defaults to selectallornone ("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, $text = null, $attributes = null, $originalValue = 0) {
962 global $CFG;
964 // Set the default text if none was specified
965 if (empty($text)) {
966 $text = get_string('selectallornone', 'form');
969 $mform = $this->_form;
970 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
972 if ($select_value == 0 || is_null($select_value)) {
973 $new_select_value = 1;
974 } else {
975 $new_select_value = 0;
978 $mform->addElement('hidden', "checkbox_controller$groupid");
979 $mform->setType("checkbox_controller$groupid", PARAM_INT);
980 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
982 // Locate all checkboxes for this group and set their value, IF the optional param was given
983 if (!is_null($select_value)) {
984 foreach ($this->_form->_elements as $element) {
985 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
986 $mform->setConstants(array($element->getAttribute('name') => $select_value));
991 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
992 $mform->registerNoSubmitButton($checkbox_controller_name);
994 // Prepare Javascript for submit element
995 $js = "\n//<![CDATA[\n";
996 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
997 $js .= <<<EOS
998 function html_quickform_toggle_checkboxes(group) {
999 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
1000 var newvalue = false;
1001 var global = eval('html_quickform_checkboxgroup' + group + ';');
1002 if (global == 1) {
1003 eval('html_quickform_checkboxgroup' + group + ' = 0;');
1004 newvalue = '';
1005 } else {
1006 eval('html_quickform_checkboxgroup' + group + ' = 1;');
1007 newvalue = 'checked';
1010 for (i = 0; i < checkboxes.length; i++) {
1011 checkboxes[i].checked = newvalue;
1014 EOS;
1015 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
1017 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
1019 $js .= "//]]>\n";
1021 require_once("$CFG->libdir/form/submitlink.php");
1022 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
1023 $submitlink->_js = $js;
1024 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
1025 $mform->addElement($submitlink);
1026 $mform->setDefault($checkbox_controller_name, $text);
1030 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1031 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1032 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1033 * get data with get_data().
1035 * @param boolean $cancel whether to show cancel button, default true
1036 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1038 function add_action_buttons($cancel = true, $submitlabel=null){
1039 if (is_null($submitlabel)){
1040 $submitlabel = get_string('savechanges');
1042 $mform =& $this->_form;
1043 if ($cancel){
1044 //when two elements we need a group
1045 $buttonarray=array();
1046 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1047 $buttonarray[] = &$mform->createElement('cancel');
1048 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1049 $mform->closeHeaderBefore('buttonar');
1050 } else {
1051 //no group needed
1052 $mform->addElement('submit', 'submitbutton', $submitlabel);
1053 $mform->closeHeaderBefore('submitbutton');
1058 * Adds an initialisation call for a standard JavaScript enhancement.
1060 * This function is designed to add an initialisation call for a JavaScript
1061 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1063 * Current options:
1064 * - Selectboxes
1065 * - smartselect: Turns a nbsp indented select box into a custom drop down
1066 * control that supports multilevel and category selection.
1067 * $enhancement = 'smartselect';
1068 * $options = array('selectablecategories' => true|false)
1070 * @since 2.0
1071 * @param string|element $element
1072 * @param string $enhancement
1073 * @param array $options
1074 * @param array $strings
1076 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1077 global $PAGE;
1078 if (is_string($element)) {
1079 $element = $this->_form->getElement($element);
1081 if (is_object($element)) {
1082 $element->_generateId();
1083 $elementid = $element->getAttribute('id');
1084 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1085 if (is_array($strings)) {
1086 foreach ($strings as $string) {
1087 if (is_array($string)) {
1088 call_user_method_array('string_for_js', $PAGE->requires, $string);
1089 } else {
1090 $PAGE->requires->string_for_js($string, 'moodle');
1098 * Returns a JS module definition for the mforms JS
1099 * @return array
1101 public static function get_js_module() {
1102 global $CFG;
1103 return array(
1104 'name' => 'mform',
1105 'fullpath' => '/lib/form/form.js',
1106 'requires' => array('base', 'node'),
1107 'strings' => array(
1108 array('showadvanced', 'form'),
1109 array('hideadvanced', 'form')
1116 * You never extend this class directly. The class methods of this class are available from
1117 * the private $this->_form property on moodleform and its children. You generally only
1118 * call methods on this class from within abstract methods that you override on moodleform such
1119 * as definition and definition_after_data
1121 * @package moodlecore
1122 * @copyright Jamie Pratt <me@jamiep.org>
1123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1125 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1126 /** @var array */
1127 var $_types = array();
1128 var $_dependencies = array();
1130 * Array of buttons that if pressed do not result in the processing of the form.
1132 * @var array
1134 var $_noSubmitButtons=array();
1136 * Array of buttons that if pressed do not result in the processing of the form.
1138 * @var array
1140 var $_cancelButtons=array();
1143 * Array whose keys are element names. If the key exists this is a advanced element
1145 * @var array
1147 var $_advancedElements = array();
1150 * Whether to display advanced elements (on page load)
1152 * @var boolean
1154 var $_showAdvanced = null;
1157 * The form name is derived from the class name of the wrapper minus the trailing form
1158 * It is a name with words joined by underscores whereas the id attribute is words joined by
1159 * underscores.
1161 * @var unknown_type
1163 var $_formName = '';
1166 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1168 * @var string
1170 var $_pageparams = '';
1173 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1175 * @global object
1176 * @staticvar int $formcounter
1177 * @param string $formName Form's name.
1178 * @param string $method (optional)Form's method defaults to 'POST'
1179 * @param mixed $action (optional)Form's action - string or moodle_url
1180 * @param string $target (optional)Form's target defaults to none
1181 * @param mixed $attributes (optional)Extra attributes for <form> tag
1182 * @access public
1184 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1185 global $CFG, $OUTPUT;
1187 static $formcounter = 1;
1189 HTML_Common::HTML_Common($attributes);
1190 $target = empty($target) ? array() : array('target' => $target);
1191 $this->_formName = $formName;
1192 if (is_a($action, 'moodle_url')){
1193 $this->_pageparams = html_writer::input_hidden_params($action);
1194 $action = $action->out_omit_querystring();
1195 } else {
1196 $this->_pageparams = '';
1198 //no 'name' atttribute for form in xhtml strict :
1199 $attributes = array('action'=>$action, 'method'=>$method,
1200 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1201 $formcounter++;
1202 $this->updateAttributes($attributes);
1204 //this is custom stuff for Moodle :
1205 $oldclass= $this->getAttribute('class');
1206 if (!empty($oldclass)){
1207 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1208 }else {
1209 $this->updateAttributes(array('class'=>'mform'));
1211 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1212 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1213 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1217 * Use this method to indicate an element in a form is an advanced field. If items in a form
1218 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1219 * form so the user can decide whether to display advanced form controls.
1221 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1223 * @param string $elementName group or element name (not the element name of something inside a group).
1224 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1226 function setAdvanced($elementName, $advanced=true){
1227 if ($advanced){
1228 $this->_advancedElements[$elementName]='';
1229 } elseif (isset($this->_advancedElements[$elementName])) {
1230 unset($this->_advancedElements[$elementName]);
1232 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1233 $this->setShowAdvanced();
1234 $this->registerNoSubmitButton('mform_showadvanced');
1236 $this->addElement('hidden', 'mform_showadvanced_last');
1237 $this->setType('mform_showadvanced_last', PARAM_INT);
1241 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1242 * display advanced elements in the form until 'Show Advanced' is pressed.
1244 * You can get the last state of the form and possibly save it for this user by using
1245 * value 'mform_showadvanced_last' in submitted data.
1247 * @param boolean $showadvancedNow
1249 function setShowAdvanced($showadvancedNow = null){
1250 if ($showadvancedNow === null){
1251 if ($this->_showAdvanced !== null){
1252 return;
1253 } else { //if setShowAdvanced is called without any preference
1254 //make the default to not show advanced elements.
1255 $showadvancedNow = get_user_preferences(
1256 moodle_strtolower($this->_formName.'_showadvanced', 0));
1259 //value of hidden element
1260 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1261 //value of button
1262 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1263 //toggle if button pressed or else stay the same
1264 if ($hiddenLast == -1) {
1265 $next = $showadvancedNow;
1266 } elseif ($buttonPressed) { //toggle on button press
1267 $next = !$hiddenLast;
1268 } else {
1269 $next = $hiddenLast;
1271 $this->_showAdvanced = $next;
1272 if ($showadvancedNow != $next){
1273 set_user_preference($this->_formName.'_showadvanced', $next);
1275 $this->setConstants(array('mform_showadvanced_last'=>$next));
1277 function getShowAdvanced(){
1278 return $this->_showAdvanced;
1283 * Accepts a renderer
1285 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
1286 * @access public
1287 * @return void
1289 function accept(&$renderer) {
1290 if (method_exists($renderer, 'setAdvancedElements')){
1291 //check for visible fieldsets where all elements are advanced
1292 //and mark these headers as advanced as well.
1293 //And mark all elements in a advanced header as advanced
1294 $stopFields = $renderer->getStopFieldSetElements();
1295 $lastHeader = null;
1296 $lastHeaderAdvanced = false;
1297 $anyAdvanced = false;
1298 foreach (array_keys($this->_elements) as $elementIndex){
1299 $element =& $this->_elements[$elementIndex];
1301 // if closing header and any contained element was advanced then mark it as advanced
1302 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1303 if ($anyAdvanced && !is_null($lastHeader)){
1304 $this->setAdvanced($lastHeader->getName());
1306 $lastHeaderAdvanced = false;
1307 unset($lastHeader);
1308 $lastHeader = null;
1309 } elseif ($lastHeaderAdvanced) {
1310 $this->setAdvanced($element->getName());
1313 if ($element->getType()=='header'){
1314 $lastHeader =& $element;
1315 $anyAdvanced = false;
1316 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1317 } elseif (isset($this->_advancedElements[$element->getName()])){
1318 $anyAdvanced = true;
1321 // the last header may not be closed yet...
1322 if ($anyAdvanced && !is_null($lastHeader)){
1323 $this->setAdvanced($lastHeader->getName());
1325 $renderer->setAdvancedElements($this->_advancedElements);
1328 parent::accept($renderer);
1332 * @param string $elementName
1334 function closeHeaderBefore($elementName){
1335 $renderer =& $this->defaultRenderer();
1336 $renderer->addStopFieldsetElements($elementName);
1340 * Should be used for all elements of a form except for select, radio and checkboxes which
1341 * clean their own data.
1343 * @param string $elementname
1344 * @param integer $paramtype use the constants PARAM_*.
1345 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1346 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1347 * It will strip all html tags. But will still let tags for multilang support
1348 * through.
1349 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1350 * html editor. Data from the editor is later cleaned before display using
1351 * format_text() function. PARAM_RAW can also be used for data that is validated
1352 * by some other way or printed by p() or s().
1353 * * PARAM_INT should be used for integers.
1354 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1355 * form actions.
1357 function setType($elementname, $paramtype) {
1358 $this->_types[$elementname] = $paramtype;
1362 * See description of setType above. This can be used to set several types at once.
1364 * @param array $paramtypes
1366 function setTypes($paramtypes) {
1367 $this->_types = $paramtypes + $this->_types;
1371 * @param array $submission
1372 * @param array $files
1374 function updateSubmission($submission, $files) {
1375 $this->_flagSubmitted = false;
1377 if (empty($submission)) {
1378 $this->_submitValues = array();
1379 } else {
1380 foreach ($submission as $key=>$s) {
1381 if (array_key_exists($key, $this->_types)) {
1382 $submission[$key] = clean_param($s, $this->_types[$key]);
1385 $this->_submitValues = $submission;
1386 $this->_flagSubmitted = true;
1389 if (empty($files)) {
1390 $this->_submitFiles = array();
1391 } else {
1392 $this->_submitFiles = $files;
1393 $this->_flagSubmitted = true;
1396 // need to tell all elements that they need to update their value attribute.
1397 foreach (array_keys($this->_elements) as $key) {
1398 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1403 * @return string
1405 function getReqHTML(){
1406 return $this->_reqHTML;
1410 * @return string
1412 function getAdvancedHTML(){
1413 return $this->_advancedHTML;
1417 * Initializes a default form value. Used to specify the default for a new entry where
1418 * no data is loaded in using moodleform::set_data()
1420 * note: $slashed param removed
1422 * @param string $elementname element name
1423 * @param mixed $values values for that element name
1424 * @access public
1425 * @return void
1427 function setDefault($elementName, $defaultValue){
1428 $this->setDefaults(array($elementName=>$defaultValue));
1429 } // end func setDefault
1431 * Add an array of buttons to the form
1432 * @param array $buttons An associative array representing help button to attach to
1433 * to the form. keys of array correspond to names of elements in form.
1434 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1435 * @param bool $suppresscheck
1436 * @param string $function
1437 * @access public
1439 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1441 debugging('function moodle_form::setHelpButtons() is deprecated');
1442 //foreach ($buttons as $elementname => $button){
1443 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1447 * Add a single button.
1449 * @deprecated use addHelpButton() instead
1450 * @param string $elementname name of the element to add the item to
1451 * @param array $button arguments to pass to function $function
1452 * @param boolean $suppresscheck whether to throw an error if the element
1453 * doesn't exist.
1454 * @param string $function - function to generate html from the arguments in $button
1455 * @param string $function
1457 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1458 global $OUTPUT;
1460 debugging('function moodle_form::setHelpButton() is deprecated');
1461 if ($function !== 'helpbutton') {
1462 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1465 $buttonargs = (array)$buttonargs;
1467 if (array_key_exists($elementname, $this->_elementIndex)) {
1468 //_elements has a numeric index, this code accesses the elements by name
1469 $element = $this->_elements[$this->_elementIndex[$elementname]];
1471 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1472 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1473 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1474 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1476 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1478 } else if (!$suppresscheck) {
1479 print_error('nonexistentformelements', 'form', '', $elementname);
1484 * Add a help button to element, only one button per element is allowed.
1486 * This is new, simplified and preferable method of setting a help icon on form elements.
1487 * It uses the new $OUTPUT->help_icon().
1489 * Typically, you will provide the same identifier and the component as you have used for the
1490 * label of the element. The string identifier with the _help suffix added is then used
1491 * as the help string.
1493 * There has to be two strings defined:
1494 * 1/ get_string($identifier, $component) - the title of the help page
1495 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1497 * @since 2.0
1498 * @param string $elementname name of the element to add the item to
1499 * @param string $identifier help string identifier without _help suffix
1500 * @param string $component component name to look the help string in
1501 * @param string $linktext optional text to display next to the icon
1502 * @param boolean $suppresscheck set to true if the element may not exist
1503 * @return void
1505 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1506 global $OUTPUT;
1507 if (array_key_exists($elementname, $this->_elementIndex)) {
1508 $element = $this->_elements[$this->_elementIndex[$elementname]];
1509 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1510 } else if (!$suppresscheck) {
1511 debugging(get_string('nonexistentformelements', 'form', $elementname));
1516 * Set constant value not overridden by _POST or _GET
1517 * note: this does not work for complex names with [] :-(
1519 * @param string $elname name of element
1520 * @param mixed $value
1521 * @return void
1523 function setConstant($elname, $value) {
1524 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1525 $element =& $this->getElement($elname);
1526 $element->onQuickFormEvent('updateValue', null, $this);
1530 * @param string $elementList
1532 function exportValues($elementList = null){
1533 $unfiltered = array();
1534 if (null === $elementList) {
1535 // iterate over all elements, calling their exportValue() methods
1536 $emptyarray = array();
1537 foreach (array_keys($this->_elements) as $key) {
1538 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1539 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1540 } else {
1541 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1544 if (is_array($value)) {
1545 // This shit throws a bogus warning in PHP 4.3.x
1546 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1549 } else {
1550 if (!is_array($elementList)) {
1551 $elementList = array_map('trim', explode(',', $elementList));
1553 foreach ($elementList as $elementName) {
1554 $value = $this->exportValue($elementName);
1555 if (PEAR::isError($value)) {
1556 return $value;
1558 //oh, stock QuickFOrm was returning array of arrays!
1559 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1563 return $unfiltered;
1566 * Adds a validation rule for the given field
1568 * If the element is in fact a group, it will be considered as a whole.
1569 * To validate grouped elements as separated entities,
1570 * use addGroupRule instead of addRule.
1572 * @param string $element Form element name
1573 * @param string $message Message to display for invalid data
1574 * @param string $type Rule type, use getRegisteredRules() to get types
1575 * @param string $format (optional)Required for extra rule data
1576 * @param string $validation (optional)Where to perform validation: "server", "client"
1577 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1578 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1579 * @access public
1581 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1583 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1584 if ($validation == 'client') {
1585 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1588 } // end func addRule
1590 * Adds a validation rule for the given group of elements
1592 * Only groups with a name can be assigned a validation rule
1593 * Use addGroupRule when you need to validate elements inside the group.
1594 * Use addRule if you need to validate the group as a whole. In this case,
1595 * the same rule will be applied to all elements in the group.
1596 * Use addRule if you need to validate the group against a function.
1598 * @param string $group Form group name
1599 * @param mixed $arg1 Array for multiple elements or error message string for one element
1600 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1601 * @param string $format (optional)Required for extra rule data
1602 * @param int $howmany (optional)How many valid elements should be in the group
1603 * @param string $validation (optional)Where to perform validation: "server", "client"
1604 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1605 * @access public
1607 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1609 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1610 if (is_array($arg1)) {
1611 foreach ($arg1 as $rules) {
1612 foreach ($rules as $rule) {
1613 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1615 if ('client' == $validation) {
1616 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1620 } elseif (is_string($arg1)) {
1622 if ($validation == 'client') {
1623 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1626 } // end func addGroupRule
1628 // }}}
1630 * Returns the client side validation script
1632 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1633 * and slightly modified to run rules per-element
1634 * Needed to override this because of an error with client side validation of grouped elements.
1636 * @access public
1637 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1639 function getValidationScript()
1641 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1642 return '';
1645 include_once('HTML/QuickForm/RuleRegistry.php');
1646 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1647 $test = array();
1648 $js_escape = array(
1649 "\r" => '\r',
1650 "\n" => '\n',
1651 "\t" => '\t',
1652 "'" => "\\'",
1653 '"' => '\"',
1654 '\\' => '\\\\'
1657 foreach ($this->_rules as $elementName => $rules) {
1658 foreach ($rules as $rule) {
1659 if ('client' == $rule['validation']) {
1660 unset($element); //TODO: find out how to properly initialize it
1662 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1663 $rule['message'] = strtr($rule['message'], $js_escape);
1665 if (isset($rule['group'])) {
1666 $group =& $this->getElement($rule['group']);
1667 // No JavaScript validation for frozen elements
1668 if ($group->isFrozen()) {
1669 continue 2;
1671 $elements =& $group->getElements();
1672 foreach (array_keys($elements) as $key) {
1673 if ($elementName == $group->getElementName($key)) {
1674 $element =& $elements[$key];
1675 break;
1678 } elseif ($dependent) {
1679 $element = array();
1680 $element[] =& $this->getElement($elementName);
1681 foreach ($rule['dependent'] as $elName) {
1682 $element[] =& $this->getElement($elName);
1684 } else {
1685 $element =& $this->getElement($elementName);
1687 // No JavaScript validation for frozen elements
1688 if (is_object($element) && $element->isFrozen()) {
1689 continue 2;
1690 } elseif (is_array($element)) {
1691 foreach (array_keys($element) as $key) {
1692 if ($element[$key]->isFrozen()) {
1693 continue 3;
1697 // Fix for bug displaying errors for elements in a group
1698 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1699 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1700 $test[$elementName][1]=$element;
1701 //end of fix
1706 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1707 // the form, and then that form field gets corrupted by the code that follows.
1708 unset($element);
1710 $js = '
1711 <script type="text/javascript">
1712 //<![CDATA[
1714 var skipClientValidation = false;
1716 function qf_errorHandler(element, _qfMsg) {
1717 div = element.parentNode;
1718 if (_qfMsg != \'\') {
1719 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1720 if (!errorSpan) {
1721 errorSpan = document.createElement("span");
1722 errorSpan.id = \'id_error_\'+element.name;
1723 errorSpan.className = "error";
1724 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1727 while (errorSpan.firstChild) {
1728 errorSpan.removeChild(errorSpan.firstChild);
1731 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1732 errorSpan.appendChild(document.createElement("br"));
1734 if (div.className.substr(div.className.length - 6, 6) != " error"
1735 && div.className != "error") {
1736 div.className += " error";
1739 return false;
1740 } else {
1741 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1742 if (errorSpan) {
1743 errorSpan.parentNode.removeChild(errorSpan);
1746 if (div.className.substr(div.className.length - 6, 6) == " error") {
1747 div.className = div.className.substr(0, div.className.length - 6);
1748 } else if (div.className == "error") {
1749 div.className = "";
1752 return true;
1755 $validateJS = '';
1756 foreach ($test as $elementName => $jsandelement) {
1757 // Fix for bug displaying errors for elements in a group
1758 //unset($element);
1759 list($jsArr,$element)=$jsandelement;
1760 //end of fix
1761 $escapedElementName = preg_replace_callback(
1762 '/[_\[\]]/',
1763 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1764 $elementName);
1765 $js .= '
1766 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1767 var value = \'\';
1768 var errFlag = new Array();
1769 var _qfGroups = {};
1770 var _qfMsg = \'\';
1771 var frm = element.parentNode;
1772 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1773 frm = frm.parentNode;
1775 ' . join("\n", $jsArr) . '
1776 return qf_errorHandler(element, _qfMsg);
1779 $validateJS .= '
1780 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1781 if (!ret && !first_focus) {
1782 first_focus = true;
1783 frm.elements[\''.$elementName.'\'].focus();
1787 // Fix for bug displaying errors for elements in a group
1788 //unset($element);
1789 //$element =& $this->getElement($elementName);
1790 //end of fix
1791 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1792 $onBlur = $element->getAttribute('onBlur');
1793 $onChange = $element->getAttribute('onChange');
1794 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1795 'onChange' => $onChange . $valFunc));
1797 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1798 $js .= '
1799 function validate_' . $this->_formName . '(frm) {
1800 if (skipClientValidation) {
1801 return true;
1803 var ret = true;
1805 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1806 var first_focus = false;
1807 ' . $validateJS . ';
1808 return ret;
1810 //]]>
1811 </script>';
1812 return $js;
1813 } // end func getValidationScript
1814 function _setDefaultRuleMessages(){
1815 foreach ($this->_rules as $field => $rulesarr){
1816 foreach ($rulesarr as $key => $rule){
1817 if ($rule['message']===null){
1818 $a=new stdClass();
1819 $a->format=$rule['format'];
1820 $str=get_string('err_'.$rule['type'], 'form', $a);
1821 if (strpos($str, '[[')!==0){
1822 $this->_rules[$field][$key]['message']=$str;
1829 function getLockOptionObject(){
1830 $result = array();
1831 foreach ($this->_dependencies as $dependentOn => $conditions){
1832 $result[$dependentOn] = array();
1833 foreach ($conditions as $condition=>$values) {
1834 $result[$dependentOn][$condition] = array();
1835 foreach ($values as $value=>$dependents) {
1836 $result[$dependentOn][$condition][$value] = array();
1837 $i = 0;
1838 foreach ($dependents as $dependent) {
1839 $elements = $this->_getElNamesRecursive($dependent);
1840 if (empty($elements)) {
1841 // probably element inside of some group
1842 $elements = array($dependent);
1844 foreach($elements as $element) {
1845 if ($element == $dependentOn) {
1846 continue;
1848 $result[$dependentOn][$condition][$value][] = $element;
1854 return array($this->getAttribute('id'), $result);
1858 * @param mixed $element
1859 * @return array
1861 function _getElNamesRecursive($element) {
1862 if (is_string($element)) {
1863 if (!$this->elementExists($element)) {
1864 return array();
1866 $element = $this->getElement($element);
1869 if (is_a($element, 'HTML_QuickForm_group')) {
1870 $elsInGroup = $element->getElements();
1871 $elNames = array();
1872 foreach ($elsInGroup as $elInGroup){
1873 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1874 // not sure if this would work - groups nested in groups
1875 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1876 } else {
1877 $elNames[] = $element->getElementName($elInGroup->getName());
1881 } else if (is_a($element, 'HTML_QuickForm_header')) {
1882 return array();
1884 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1885 return array();
1887 } else if (method_exists($element, 'getPrivateName')) {
1888 return array($element->getPrivateName());
1890 } else {
1891 $elNames = array($element->getName());
1894 return $elNames;
1898 * Adds a dependency for $elementName which will be disabled if $condition is met.
1899 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1900 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1901 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1902 * of the $dependentOn element is $condition (such as equal) to $value.
1904 * @param string $elementName the name of the element which will be disabled
1905 * @param string $dependentOn the name of the element whose state will be checked for
1906 * condition
1907 * @param string $condition the condition to check
1908 * @param mixed $value used in conjunction with condition.
1910 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1911 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1912 $this->_dependencies[$dependentOn] = array();
1914 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1915 $this->_dependencies[$dependentOn][$condition] = array();
1917 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1918 $this->_dependencies[$dependentOn][$condition][$value] = array();
1920 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1923 function registerNoSubmitButton($buttonname){
1924 $this->_noSubmitButtons[]=$buttonname;
1928 * @param string $buttonname
1929 * @return mixed
1931 function isNoSubmitButton($buttonname){
1932 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1936 * @param string $buttonname
1938 function _registerCancelButton($addfieldsname){
1939 $this->_cancelButtons[]=$addfieldsname;
1942 * Displays elements without HTML input tags.
1943 * This method is different to freeze() in that it makes sure no hidden
1944 * elements are included in the form.
1945 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1947 * This function also removes all previously defined rules.
1949 * @param mixed $elementList array or string of element(s) to be frozen
1950 * @access public
1952 function hardFreeze($elementList=null)
1954 if (!isset($elementList)) {
1955 $this->_freezeAll = true;
1956 $elementList = array();
1957 } else {
1958 if (!is_array($elementList)) {
1959 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1961 $elementList = array_flip($elementList);
1964 foreach (array_keys($this->_elements) as $key) {
1965 $name = $this->_elements[$key]->getName();
1966 if ($this->_freezeAll || isset($elementList[$name])) {
1967 $this->_elements[$key]->freeze();
1968 $this->_elements[$key]->setPersistantFreeze(false);
1969 unset($elementList[$name]);
1971 // remove all rules
1972 $this->_rules[$name] = array();
1973 // if field is required, remove the rule
1974 $unset = array_search($name, $this->_required);
1975 if ($unset !== false) {
1976 unset($this->_required[$unset]);
1981 if (!empty($elementList)) {
1982 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);
1984 return true;
1987 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1989 * This function also removes all previously defined rules of elements it freezes.
1991 * throws HTML_QuickForm_Error
1993 * @param array $elementList array or string of element(s) not to be frozen
1994 * @access public
1996 function hardFreezeAllVisibleExcept($elementList)
1998 $elementList = array_flip($elementList);
1999 foreach (array_keys($this->_elements) as $key) {
2000 $name = $this->_elements[$key]->getName();
2001 $type = $this->_elements[$key]->getType();
2003 if ($type == 'hidden'){
2004 // leave hidden types as they are
2005 } elseif (!isset($elementList[$name])) {
2006 $this->_elements[$key]->freeze();
2007 $this->_elements[$key]->setPersistantFreeze(false);
2009 // remove all rules
2010 $this->_rules[$name] = array();
2011 // if field is required, remove the rule
2012 $unset = array_search($name, $this->_required);
2013 if ($unset !== false) {
2014 unset($this->_required[$unset]);
2018 return true;
2021 * Tells whether the form was already submitted
2023 * This is useful since the _submitFiles and _submitValues arrays
2024 * may be completely empty after the trackSubmit value is removed.
2026 * @access public
2027 * @return bool
2029 function isSubmitted()
2031 return parent::isSubmitted() && (!$this->isFrozen());
2037 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2038 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2040 * Stylesheet is part of standard theme and should be automatically included.
2042 * @package moodlecore
2043 * @copyright Jamie Pratt <me@jamiep.org>
2044 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2046 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2049 * Element template array
2050 * @var array
2051 * @access private
2053 var $_elementTemplates;
2055 * Template used when opening a hidden fieldset
2056 * (i.e. a fieldset that is opened when there is no header element)
2057 * @var string
2058 * @access private
2060 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2062 * Header Template string
2063 * @var string
2064 * @access private
2066 var $_headerTemplate =
2067 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2070 * Template used when opening a fieldset
2071 * @var string
2072 * @access private
2074 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2077 * Template used when closing a fieldset
2078 * @var string
2079 * @access private
2081 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2084 * Required Note template string
2085 * @var string
2086 * @access private
2088 var $_requiredNoteTemplate =
2089 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2091 var $_advancedElements = array();
2094 * Whether to display advanced elements (on page load)
2096 * @var integer 1 means show 0 means hide
2098 var $_showAdvanced;
2100 function MoodleQuickForm_Renderer(){
2101 // switch next two lines for ol li containers for form items.
2102 // $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>');
2103 $this->_elementTemplates = array(
2104 '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>',
2106 '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>',
2108 '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>',
2110 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2112 'nodisplay'=>'');
2114 parent::HTML_QuickForm_Renderer_Tableless();
2118 * @param array $elements
2120 function setAdvancedElements($elements){
2121 $this->_advancedElements = $elements;
2125 * What to do when starting the form
2127 * @param object $form MoodleQuickForm
2129 function startForm(&$form){
2130 $this->_reqHTML = $form->getReqHTML();
2131 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2132 $this->_advancedHTML = $form->getAdvancedHTML();
2133 $this->_showAdvanced = $form->getShowAdvanced();
2134 parent::startForm($form);
2135 if ($form->isFrozen()){
2136 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2137 } else {
2138 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2139 $this->_hiddenHtml .= $form->_pageparams;
2146 * @param object $group Passed by reference
2147 * @param mixed $required
2148 * @param mixed $error
2150 function startGroup(&$group, $required, $error){
2151 if (method_exists($group, 'getElementTemplateType')){
2152 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2153 }else{
2154 $html = $this->_elementTemplates['default'];
2157 if ($this->_showAdvanced){
2158 $advclass = ' advanced';
2159 } else {
2160 $advclass = ' advanced hide';
2162 if (isset($this->_advancedElements[$group->getName()])){
2163 $html =str_replace(' {advanced}', $advclass, $html);
2164 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2165 } else {
2166 $html =str_replace(' {advanced}', '', $html);
2167 $html =str_replace('{advancedimg}', '', $html);
2169 if (method_exists($group, 'getHelpButton')){
2170 $html =str_replace('{help}', $group->getHelpButton(), $html);
2171 }else{
2172 $html =str_replace('{help}', '', $html);
2174 $html =str_replace('{name}', $group->getName(), $html);
2175 $html =str_replace('{type}', 'fgroup', $html);
2177 $this->_templates[$group->getName()]=$html;
2178 // Fix for bug in tableless quickforms that didn't allow you to stop a
2179 // fieldset before a group of elements.
2180 // if the element name indicates the end of a fieldset, close the fieldset
2181 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2182 && $this->_fieldsetsOpen > 0
2184 $this->_html .= $this->_closeFieldsetTemplate;
2185 $this->_fieldsetsOpen--;
2187 parent::startGroup($group, $required, $error);
2190 * @param object $element
2191 * @param mixed $required
2192 * @param mixed $error
2194 function renderElement(&$element, $required, $error){
2195 //manipulate id of all elements before rendering
2196 if (!is_null($element->getAttribute('id'))) {
2197 $id = $element->getAttribute('id');
2198 } else {
2199 $id = $element->getName();
2201 //strip qf_ prefix and replace '[' with '_' and strip ']'
2202 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
2203 if (strpos($id, 'id_') !== 0){
2204 $element->updateAttributes(array('id'=>'id_'.$id));
2207 //adding stuff to place holders in template
2208 //check if this is a group element first
2209 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2210 // so it gets substitutions for *each* element
2211 $html = $this->_groupElementTemplate;
2213 elseif (method_exists($element, 'getElementTemplateType')){
2214 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2215 }else{
2216 $html = $this->_elementTemplates['default'];
2218 if ($this->_showAdvanced){
2219 $advclass = ' advanced';
2220 } else {
2221 $advclass = ' advanced hide';
2223 if (isset($this->_advancedElements[$element->getName()])){
2224 $html =str_replace(' {advanced}', $advclass, $html);
2225 } else {
2226 $html =str_replace(' {advanced}', '', $html);
2228 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2229 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2230 } else {
2231 $html =str_replace('{advancedimg}', '', $html);
2233 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2234 $html =str_replace('{name}', $element->getName(), $html);
2235 if (method_exists($element, 'getHelpButton')){
2236 $html = str_replace('{help}', $element->getHelpButton(), $html);
2237 }else{
2238 $html = str_replace('{help}', '', $html);
2241 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2242 $this->_groupElementTemplate = $html;
2244 elseif (!isset($this->_templates[$element->getName()])) {
2245 $this->_templates[$element->getName()] = $html;
2248 parent::renderElement($element, $required, $error);
2252 * @global moodle_page $PAGE
2253 * @param object $form Passed by reference
2255 function finishForm(&$form){
2256 global $PAGE;
2257 if ($form->isFrozen()){
2258 $this->_hiddenHtml = '';
2260 parent::finishForm($form);
2261 if (!$form->isFrozen()) {
2262 $args = $form->getLockOptionObject();
2263 if (count($args[1]) > 0) {
2264 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, false, moodleform::get_js_module());
2269 * Called when visiting a header element
2271 * @param object $header An HTML_QuickForm_header element being visited
2272 * @access public
2273 * @return void
2274 * @global moodle_page $PAGE
2276 function renderHeader(&$header) {
2277 global $PAGE;
2279 $name = $header->getName();
2281 $id = empty($name) ? '' : ' id="' . $name . '"';
2282 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2283 if (is_null($header->_text)) {
2284 $header_html = '';
2285 } elseif (!empty($name) && isset($this->_templates[$name])) {
2286 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2287 } else {
2288 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2291 if (isset($this->_advancedElements[$name])){
2292 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2293 $elementName='mform_showadvanced';
2294 if ($this->_showAdvanced==0){
2295 $buttonlabel = get_string('showadvanced', 'form');
2296 } else {
2297 $buttonlabel = get_string('hideadvanced', 'form');
2299 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2300 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2301 $header_html = str_replace('{button}', $button, $header_html);
2302 } else {
2303 $header_html =str_replace('{advancedimg}', '', $header_html);
2304 $header_html = str_replace('{button}', '', $header_html);
2307 if ($this->_fieldsetsOpen > 0) {
2308 $this->_html .= $this->_closeFieldsetTemplate;
2309 $this->_fieldsetsOpen--;
2312 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2313 if ($this->_showAdvanced){
2314 $advclass = ' class="advanced"';
2315 } else {
2316 $advclass = ' class="advanced hide"';
2318 if (isset($this->_advancedElements[$name])){
2319 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2320 } else {
2321 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2323 $this->_html .= $openFieldsetTemplate . $header_html;
2324 $this->_fieldsetsOpen++;
2325 } // end func renderHeader
2327 function getStopFieldsetElements(){
2328 return $this->_stopFieldsetElements;
2333 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2334 * @name $_HTML_QuickForm_default_renderer
2336 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2338 /** Please keep this list in alphabetical order. */
2339 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2340 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2341 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2342 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2343 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2344 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2345 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2346 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2347 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2348 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2349 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2350 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2351 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2352 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2353 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2354 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2355 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2356 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2357 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2358 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2359 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2360 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2361 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2362 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2363 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2364 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2365 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2366 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2367 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2368 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2369 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2370 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2371 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2372 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2373 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2374 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');