2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
25 * See examples of use of this library in course/edit.php and course/edit_form.php
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
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';
46 require_once 'HTML/QuickForm/Rule.php';
48 require_once $CFG->libdir.'/filelib.php';
50 define('EDITOR_UNLIMITED_FILES', -1);
53 * Callback called when PEAR throws an error
55 * @param PEAR_Error $error
57 function pear_handle_error($error){
58 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
59 echo '<br /> <strong>Backtrace </strong>:';
60 print_object($error->backtrace);
63 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
64 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
69 * @staticvar bool $done
70 * @global moodle_page $PAGE
72 function form_init_date_js() {
76 $module = 'moodle-form-dateselector';
77 $function = 'M.form.dateselector.init_date_selectors';
78 $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
79 $PAGE->requires->yui_module($module, $function, $config);
85 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
86 * use this class you should write a class definition which extends this class or a more specific
87 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
89 * You will write your own definition() method which performs the form set up.
92 * @copyright Jamie Pratt <me@jamiep.org>
93 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
95 abstract class moodleform {
97 protected $_formname; // form name
99 * quickform object definition
101 * @var MoodleQuickForm MoodleQuickForm
109 protected $_customdata;
111 * definition_after_data executed flag
112 * @var object definition_finalized
114 protected $_definition_finalized = false;
117 * The constructor function calls the abstract function definition() and it will then
118 * process and clean and attempt to validate incoming data.
120 * It will call your custom validate method to validate data and will also check any rules
121 * you have specified in definition using addRule
123 * The name of the form (id attribute of the form) is automatically generated depending on
124 * the name you gave the class extending moodleform. You should call your class something
127 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
128 * current url. If a moodle_url object then outputs params as hidden variables.
129 * @param array $customdata if your form defintion method needs access to data such as $course
130 * $cm, etc. to construct the form definition then pass it in this array. You can
131 * use globals for somethings.
132 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
133 * be merged and used as incoming data to the form.
134 * @param string $target target frame for form submission. You will rarely use this. Don't use
135 * it if you don't need to as the target attribute is deprecated in xhtml
137 * @param mixed $attributes you can pass a string of html attributes here or an array.
138 * @param bool $editable
139 * @return object moodleform
141 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
143 $action = strip_querystring(qualified_me());
145 // Assign custom data first, so that get_form_identifier can use it.
146 $this->_customdata = $customdata;
147 $this->_formname = $this->get_form_identifier();
149 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
151 $this->_form->hardFreeze();
156 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
157 $this->_form->setType('sesskey', PARAM_RAW);
158 $this->_form->setDefault('sesskey', sesskey());
159 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
160 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
161 $this->_form->setDefault('_qf__'.$this->_formname, 1);
162 $this->_form->_setDefaultRuleMessages();
164 // we have to know all input types before processing submission ;-)
165 $this->_process_submission($method);
169 * It should returns unique identifier for the form.
170 * Currently it will return class name, but in case two same forms have to be
171 * rendered on same page then override function to get unique form identifier.
172 * e.g This is used on multiple self enrollments page.
174 * @return string form identifier.
176 protected function get_form_identifier() {
177 return get_class($this);
181 * To autofocus on first form element or first element with error.
183 * @param string $name if this is set then the focus is forced to a field with this name
185 * @return string javascript to select form element with first error or
186 * first element if no errors. Use this as a parameter
187 * when calling print_header
189 function focus($name=NULL) {
190 $form =& $this->_form;
191 $elkeys = array_keys($form->_elementIndex);
193 if (isset($form->_errors) && 0 != count($form->_errors)){
194 $errorkeys = array_keys($form->_errors);
195 $elkeys = array_intersect($elkeys, $errorkeys);
199 if ($error or empty($name)) {
201 while (empty($names) and !empty($elkeys)) {
202 $el = array_shift($elkeys);
203 $names = $form->_getElNamesRecursive($el);
205 if (!empty($names)) {
206 $name = array_shift($names);
212 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
219 * Internal method. Alters submitted data to be suitable for quickforms processing.
220 * Must be called when the form is fully set up.
222 * @param string $method
224 function _process_submission($method) {
225 $submission = array();
226 if ($method == 'post') {
227 if (!empty($_POST)) {
228 $submission = $_POST;
231 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
234 // following trick is needed to enable proper sesskey checks when using GET forms
235 // the _qf__.$this->_formname serves as a marker that form was actually submitted
236 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
237 if (!confirm_sesskey()) {
238 print_error('invalidsesskey');
242 $submission = array();
246 $this->_form->updateSubmission($submission, $files);
250 * Internal method. Validates all old-style deprecated uploaded files.
251 * The new way is to upload files via repository api.
255 * @param array $files
256 * @return bool|array Success or an array of errors
258 function _validate_files(&$files) {
259 global $CFG, $COURSE;
263 if (empty($_FILES)) {
264 // we do not need to do any checks because no files were submitted
265 // note: server side rules do not work for files - use custom verification in validate() instead
270 $filenames = array();
272 // now check that we really want each file
273 foreach ($_FILES as $elname=>$file) {
274 $required = $this->_form->isElementRequired($elname);
276 if ($file['error'] == 4 and $file['size'] == 0) {
278 $errors[$elname] = get_string('required');
280 unset($_FILES[$elname]);
284 if (!empty($file['error'])) {
285 $errors[$elname] = file_get_upload_error($file['error']);
286 unset($_FILES[$elname]);
290 if (!is_uploaded_file($file['tmp_name'])) {
291 // TODO: improve error message
292 $errors[$elname] = get_string('error');
293 unset($_FILES[$elname]);
297 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
298 // hmm, this file was not requested
299 unset($_FILES[$elname]);
304 // TODO: rethink the file scanning MDL-19380
305 if ($CFG->runclamonupload) {
306 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
307 $errors[$elname] = $_FILES[$elname]['uploadlog'];
308 unset($_FILES[$elname]);
313 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
314 if ($filename === '') {
315 // TODO: improve error message - wrong chars
316 $errors[$elname] = get_string('error');
317 unset($_FILES[$elname]);
320 if (in_array($filename, $filenames)) {
321 // TODO: improve error message - duplicate name
322 $errors[$elname] = get_string('error');
323 unset($_FILES[$elname]);
326 $filenames[] = $filename;
327 $_FILES[$elname]['name'] = $filename;
329 $files[$elname] = $_FILES[$elname]['tmp_name'];
332 // return errors if found
333 if (count($errors) == 0){
343 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
344 * form definition (new entry form); this function is used to load in data where values
345 * already exist and data is being edited (edit entry form).
347 * note: $slashed param removed
349 * @param mixed $default_values object or array of default values
351 function set_data($default_values) {
352 if (is_object($default_values)) {
353 $default_values = (array)$default_values;
355 $this->_form->setDefaults($default_values);
361 function set_upload_manager($um=false) {
362 debugging('Old file uploads can not be used any more, please use new filepicker element');
366 * Check that form was submitted. Does not check validity of submitted data.
368 * @return bool true if form properly submitted
370 function is_submitted() {
371 return $this->_form->isSubmitted();
375 * @staticvar bool $nosubmit
377 function no_submit_button_pressed(){
378 static $nosubmit = null; // one check is enough
379 if (!is_null($nosubmit)){
382 $mform =& $this->_form;
384 if (!$this->is_submitted()){
387 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
388 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
398 * Check that form data is valid.
399 * You should almost always use this, rather than {@see validate_defined_fields}
401 * @staticvar bool $validated
402 * @return bool true if form data valid
404 function is_validated() {
405 //finalize the form definition before any processing
406 if (!$this->_definition_finalized) {
407 $this->_definition_finalized = true;
408 $this->definition_after_data();
411 return $this->validate_defined_fields();
417 * You almost always want to call {@see is_validated} instead of this
418 * because it calls {@see definition_after_data} first, before validating the form,
419 * which is what you want in 99% of cases.
421 * This is provided as a separate function for those special cases where
422 * you want the form validated before definition_after_data is called
423 * for example, to selectively add new elements depending on a no_submit_button press,
424 * but only when the form is valid when the no_submit_button is pressed,
426 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
427 * is NOT to validate the form when a no submit button has been pressed.
428 * pass true here to override this behaviour
430 * @return bool true if form data valid
432 function validate_defined_fields($validateonnosubmit=false) {
433 static $validated = null; // one validation is enough
434 $mform =& $this->_form;
435 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
437 } elseif ($validated === null) {
438 $internal_val = $mform->validate();
441 $file_val = $this->_validate_files($files);
442 if ($file_val !== true) {
443 if (!empty($file_val)) {
444 foreach ($file_val as $element=>$msg) {
445 $mform->setElementError($element, $msg);
451 $data = $mform->exportValues();
452 $moodle_val = $this->validation($data, $files);
453 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
454 // non-empty array means errors
455 foreach ($moodle_val as $element=>$msg) {
456 $mform->setElementError($element, $msg);
461 // anything else means validation ok
465 $validated = ($internal_val and $moodle_val and $file_val);
471 * Return true if a cancel button has been pressed resulting in the form being submitted.
473 * @return boolean true if a cancel button has been pressed
475 function is_cancelled(){
476 $mform =& $this->_form;
477 if ($mform->isSubmitted()){
478 foreach ($mform->_cancelButtons as $cancelbutton){
479 if (optional_param($cancelbutton, 0, PARAM_RAW)){
488 * Return submitted data if properly submitted or returns NULL if validation fails or
489 * if there is no submitted data.
491 * note: $slashed param removed
493 * @return object submitted data; NULL if not valid or not submitted or cancelled
495 function get_data() {
496 $mform =& $this->_form;
498 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
499 $data = $mform->exportValues();
500 unset($data['sesskey']); // we do not need to return sesskey
501 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
505 return (object)$data;
513 * Return submitted data without validation or NULL if there is no submitted data.
514 * note: $slashed param removed
516 * @return object submitted data; NULL if not submitted
518 function get_submitted_data() {
519 $mform =& $this->_form;
521 if ($this->is_submitted()) {
522 $data = $mform->exportValues();
523 unset($data['sesskey']); // we do not need to return sesskey
524 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
528 return (object)$data;
536 * Save verified uploaded files into directory. Upload process can be customised from definition()
537 * NOTE: please use save_stored_file() or save_file()
539 * @return bool Always false
541 function save_files($destination) {
542 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
547 * Returns name of uploaded file.
550 * @param string $elname, first element if null
551 * @return mixed false in case of failure, string if ok
553 function get_new_filename($elname=null) {
556 if (!$this->is_submitted() or !$this->is_validated()) {
560 if (is_null($elname)) {
561 if (empty($_FILES)) {
565 $elname = key($_FILES);
568 if (empty($elname)) {
572 $element = $this->_form->getElement($elname);
574 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
575 $values = $this->_form->exportValues($elname);
576 if (empty($values[$elname])) {
579 $draftid = $values[$elname];
580 $fs = get_file_storage();
581 $context = get_context_instance(CONTEXT_USER, $USER->id);
582 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
585 $file = reset($files);
586 return $file->get_filename();
589 if (!isset($_FILES[$elname])) {
593 return $_FILES[$elname]['name'];
597 * Save file to standard filesystem
600 * @param string $elname name of element
601 * @param string $pathname full path name of file
602 * @param bool $override override file if exists
603 * @return bool success
605 function save_file($elname, $pathname, $override=false) {
608 if (!$this->is_submitted() or !$this->is_validated()) {
611 if (file_exists($pathname)) {
613 if (!@unlink($pathname)) {
621 $element = $this->_form->getElement($elname);
623 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
624 $values = $this->_form->exportValues($elname);
625 if (empty($values[$elname])) {
628 $draftid = $values[$elname];
629 $fs = get_file_storage();
630 $context = get_context_instance(CONTEXT_USER, $USER->id);
631 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
634 $file = reset($files);
636 return $file->copy_content_to($pathname);
638 } else if (isset($_FILES[$elname])) {
639 return copy($_FILES[$elname]['tmp_name'], $pathname);
646 * Returns a temporary file, do not forget to delete after not needed any more.
648 * @param string $elname
649 * @return string or false
651 function save_temp_file($elname) {
652 if (!$this->get_new_filename($elname)) {
655 if (!$dir = make_upload_directory('temp/forms')) {
658 if (!$tempfile = tempnam($dir, 'tempup_')) {
661 if (!$this->save_file($elname, $tempfile, true)) {
662 // something went wrong
671 * Get draft files of a form element
672 * This is a protected method which will be used only inside moodleforms
674 * @global object $USER
675 * @param string $elname name of element
678 protected function get_draft_files($elname) {
681 if (!$this->is_submitted()) {
685 $element = $this->_form->getElement($elname);
687 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
688 $values = $this->_form->exportValues($elname);
689 if (empty($values[$elname])) {
692 $draftid = $values[$elname];
693 $fs = get_file_storage();
694 $context = get_context_instance(CONTEXT_USER, $USER->id);
695 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
704 * Save file to local filesystem pool
707 * @param string $elname name of element
708 * @param int $newcontextid
709 * @param string $newfilearea
710 * @param string $newfilepath
711 * @param string $newfilename - use specified filename, if not specified name of uploaded file used
712 * @param bool $overwrite - overwrite file if exists
713 * @param int $newuserid - new userid if required
714 * @return mixed stored_file object or false if error; may throw exception if duplicate found
716 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
717 $newfilename=null, $overwrite=false, $newuserid=null) {
720 if (!$this->is_submitted() or !$this->is_validated()) {
724 if (empty($newuserid)) {
725 $newuserid = $USER->id;
728 $element = $this->_form->getElement($elname);
729 $fs = get_file_storage();
731 if ($element instanceof MoodleQuickForm_filepicker) {
732 $values = $this->_form->exportValues($elname);
733 if (empty($values[$elname])) {
736 $draftid = $values[$elname];
737 $context = get_context_instance(CONTEXT_USER, $USER->id);
738 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
741 $file = reset($files);
742 if (is_null($newfilename)) {
743 $newfilename = $file->get_filename();
747 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
748 if (!$oldfile->delete()) {
754 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
755 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
756 return $fs->create_file_from_storedfile($file_record, $file);
758 } else if (isset($_FILES[$elname])) {
759 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
762 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
763 if (!$oldfile->delete()) {
769 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
770 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
771 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
778 * Get content of uploaded file.
781 * @param $element name of file upload element
782 * @return mixed false in case of failure, string if ok
784 function get_file_content($elname) {
787 if (!$this->is_submitted() or !$this->is_validated()) {
791 $element = $this->_form->getElement($elname);
793 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
794 $values = $this->_form->exportValues($elname);
795 if (empty($values[$elname])) {
798 $draftid = $values[$elname];
799 $fs = get_file_storage();
800 $context = get_context_instance(CONTEXT_USER, $USER->id);
801 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
804 $file = reset($files);
806 return $file->get_content();
808 } else if (isset($_FILES[$elname])) {
809 return file_get_contents($_FILES[$elname]['tmp_name']);
819 //finalize the form definition if not yet done
820 if (!$this->_definition_finalized) {
821 $this->_definition_finalized = true;
822 $this->definition_after_data();
824 $this->_form->display();
828 * Abstract method - always override!
830 protected abstract function definition();
833 * Dummy stub method - override if you need to setup the form depending on current
834 * values. This method is called after definition(), data submission and set_data().
835 * All form setup that is dependent on form values should go in here.
837 function definition_after_data(){
841 * Dummy stub method - override if you needed to perform some extra validation.
842 * If there are errors return array of errors ("fieldname"=>"error message"),
843 * otherwise true if ok.
845 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
847 * @param array $data array of ("fieldname"=>value) of submitted data
848 * @param array $files array of uploaded files "element_name"=>tmp_file_path
849 * @return array of "element_name"=>"error_description" if there are errors,
850 * or an empty array if everything is OK (true allowed for backwards compatibility too).
852 function validation($data, $files) {
857 * Method to add a repeating group of elements to a form.
859 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
860 * @param integer $repeats no of times to repeat elements initially
861 * @param array $options Array of options to apply to elements. Array keys are element names.
862 * This is an array of arrays. The second sets of keys are the option types
864 * 'default' - default value is value
865 * 'type' - PARAM_* constant is value
866 * 'helpbutton' - helpbutton params array is value
867 * 'disabledif' - last three moodleform::disabledIf()
868 * params are value as an array
869 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
870 * @param string $addfieldsname name for button to add more fields
871 * @param int $addfieldsno how many fields to add at a time
872 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
873 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
874 * @return int no of repeats of element in this page
876 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
877 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
878 if ($addstring===null){
879 $addstring = get_string('addfields', 'form', $addfieldsno);
881 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
883 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
884 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
885 if (!empty($addfields)){
886 $repeats += $addfieldsno;
888 $mform =& $this->_form;
889 $mform->registerNoSubmitButton($addfieldsname);
890 $mform->addElement('hidden', $repeathiddenname, $repeats);
891 $mform->setType($repeathiddenname, PARAM_INT);
892 //value not to be overridden by submitted value
893 $mform->setConstants(array($repeathiddenname=>$repeats));
894 $namecloned = array();
895 for ($i = 0; $i < $repeats; $i++) {
896 foreach ($elementobjs as $elementobj){
897 $elementclone = fullclone($elementobj);
898 $name = $elementclone->getName();
899 $namecloned[] = $name;
901 $elementclone->setName($name."[$i]");
903 if (is_a($elementclone, 'HTML_QuickForm_header')) {
904 $value = $elementclone->_text;
905 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
908 $value=$elementclone->getLabel();
909 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
913 $mform->addElement($elementclone);
916 for ($i=0; $i<$repeats; $i++) {
917 foreach ($options as $elementname => $elementoptions){
918 $pos=strpos($elementname, '[');
920 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
921 $realelementname .= substr($elementname, $pos+1);
923 $realelementname = $elementname."[$i]";
925 foreach ($elementoptions as $option => $params){
929 $mform->setDefault($realelementname, $params);
932 $params = array_merge(array($realelementname), $params);
933 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
936 foreach ($namecloned as $num => $name){
937 if ($params[0] == $name){
938 $params[0] = $params[0]."[$i]";
942 $params = array_merge(array($realelementname), $params);
943 call_user_func_array(array(&$mform, 'disabledIf'), $params);
946 if (is_string($params)){
947 $params = array(null, $params, null, 'client');
949 $params = array_merge(array($realelementname), $params);
950 call_user_func_array(array(&$mform, 'addRule'), $params);
957 $mform->addElement('submit', $addfieldsname, $addstring);
959 if (!$addbuttoninside) {
960 $mform->closeHeaderBefore($addfieldsname);
967 * Adds a link/button that controls the checked state of a group of checkboxes.
970 * @param int $groupid The id of the group of advcheckboxes this element controls
971 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
972 * @param array $attributes associative array of HTML attributes
973 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
975 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
978 // Set the default text if none was specified
980 $text = get_string('selectallornone', 'form');
983 $mform = $this->_form;
984 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
986 if ($select_value == 0 || is_null($select_value)) {
987 $new_select_value = 1;
989 $new_select_value = 0;
992 $mform->addElement('hidden', "checkbox_controller$groupid");
993 $mform->setType("checkbox_controller$groupid", PARAM_INT);
994 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
996 // Locate all checkboxes for this group and set their value, IF the optional param was given
997 if (!is_null($select_value)) {
998 foreach ($this->_form->_elements as $element) {
999 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
1000 $mform->setConstants(array($element->getAttribute('name') => $select_value));
1005 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
1006 $mform->registerNoSubmitButton($checkbox_controller_name);
1008 // Prepare Javascript for submit element
1009 $js = "\n//<![CDATA[\n";
1010 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
1012 function html_quickform_toggle_checkboxes(group) {
1013 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
1014 var newvalue = false;
1015 var global = eval('html_quickform_checkboxgroup' + group + ';');
1017 eval('html_quickform_checkboxgroup' + group + ' = 0;');
1020 eval('html_quickform_checkboxgroup' + group + ' = 1;');
1021 newvalue = 'checked';
1024 for (i = 0; i < checkboxes.length; i++) {
1025 checkboxes[i].checked = newvalue;
1029 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
1031 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
1035 require_once("$CFG->libdir/form/submitlink.php");
1036 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
1037 $submitlink->_js = $js;
1038 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
1039 $mform->addElement($submitlink);
1040 $mform->setDefault($checkbox_controller_name, $text);
1044 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1045 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1046 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1047 * get data with get_data().
1049 * @param boolean $cancel whether to show cancel button, default true
1050 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1052 function add_action_buttons($cancel = true, $submitlabel=null){
1053 if (is_null($submitlabel)){
1054 $submitlabel = get_string('savechanges');
1056 $mform =& $this->_form;
1058 //when two elements we need a group
1059 $buttonarray=array();
1060 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1061 $buttonarray[] = &$mform->createElement('cancel');
1062 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1063 $mform->closeHeaderBefore('buttonar');
1066 $mform->addElement('submit', 'submitbutton', $submitlabel);
1067 $mform->closeHeaderBefore('submitbutton');
1072 * Adds an initialisation call for a standard JavaScript enhancement.
1074 * This function is designed to add an initialisation call for a JavaScript
1075 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1079 * - smartselect: Turns a nbsp indented select box into a custom drop down
1080 * control that supports multilevel and category selection.
1081 * $enhancement = 'smartselect';
1082 * $options = array('selectablecategories' => true|false)
1085 * @param string|element $element
1086 * @param string $enhancement
1087 * @param array $options
1088 * @param array $strings
1090 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1092 if (is_string($element)) {
1093 $element = $this->_form->getElement($element);
1095 if (is_object($element)) {
1096 $element->_generateId();
1097 $elementid = $element->getAttribute('id');
1098 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1099 if (is_array($strings)) {
1100 foreach ($strings as $string) {
1101 if (is_array($string)) {
1102 call_user_method_array('string_for_js', $PAGE->requires, $string);
1104 $PAGE->requires->string_for_js($string, 'moodle');
1112 * Returns a JS module definition for the mforms JS
1115 public static function get_js_module() {
1119 'fullpath' => '/lib/form/form.js',
1120 'requires' => array('base', 'node'),
1122 array('showadvanced', 'form'),
1123 array('hideadvanced', 'form')
1130 * You never extend this class directly. The class methods of this class are available from
1131 * the private $this->_form property on moodleform and its children. You generally only
1132 * call methods on this class from within abstract methods that you override on moodleform such
1133 * as definition and definition_after_data
1135 * @package moodlecore
1136 * @copyright Jamie Pratt <me@jamiep.org>
1137 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1139 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1141 var $_types = array();
1142 var $_dependencies = array();
1144 * Array of buttons that if pressed do not result in the processing of the form.
1148 var $_noSubmitButtons=array();
1150 * Array of buttons that if pressed do not result in the processing of the form.
1154 var $_cancelButtons=array();
1157 * Array whose keys are element names. If the key exists this is a advanced element
1161 var $_advancedElements = array();
1164 * Whether to display advanced elements (on page load)
1168 var $_showAdvanced = null;
1171 * The form name is derived from the class name of the wrapper minus the trailing form
1172 * It is a name with words joined by underscores whereas the id attribute is words joined by
1177 var $_formName = '';
1180 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1184 var $_pageparams = '';
1187 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1190 * @staticvar int $formcounter
1191 * @param string $formName Form's name.
1192 * @param string $method (optional)Form's method defaults to 'POST'
1193 * @param mixed $action (optional)Form's action - string or moodle_url
1194 * @param string $target (optional)Form's target defaults to none
1195 * @param mixed $attributes (optional)Extra attributes for <form> tag
1198 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1199 global $CFG, $OUTPUT;
1201 static $formcounter = 1;
1203 HTML_Common::HTML_Common($attributes);
1204 $target = empty($target) ? array() : array('target' => $target);
1205 $this->_formName = $formName;
1206 if (is_a($action, 'moodle_url')){
1207 $this->_pageparams = html_writer::input_hidden_params($action);
1208 $action = $action->out_omit_querystring();
1210 $this->_pageparams = '';
1212 //no 'name' atttribute for form in xhtml strict :
1213 $attributes = array('action'=>$action, 'method'=>$method,
1214 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1216 $this->updateAttributes($attributes);
1218 //this is custom stuff for Moodle :
1219 $oldclass= $this->getAttribute('class');
1220 if (!empty($oldclass)){
1221 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1223 $this->updateAttributes(array('class'=>'mform'));
1225 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1226 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1227 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1231 * Use this method to indicate an element in a form is an advanced field. If items in a form
1232 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1233 * form so the user can decide whether to display advanced form controls.
1235 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1237 * @param string $elementName group or element name (not the element name of something inside a group).
1238 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1240 function setAdvanced($elementName, $advanced=true){
1242 $this->_advancedElements[$elementName]='';
1243 } elseif (isset($this->_advancedElements[$elementName])) {
1244 unset($this->_advancedElements[$elementName]);
1246 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1247 $this->setShowAdvanced();
1248 $this->registerNoSubmitButton('mform_showadvanced');
1250 $this->addElement('hidden', 'mform_showadvanced_last');
1251 $this->setType('mform_showadvanced_last', PARAM_INT);
1255 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1256 * display advanced elements in the form until 'Show Advanced' is pressed.
1258 * You can get the last state of the form and possibly save it for this user by using
1259 * value 'mform_showadvanced_last' in submitted data.
1261 * @param boolean $showadvancedNow
1263 function setShowAdvanced($showadvancedNow = null){
1264 if ($showadvancedNow === null){
1265 if ($this->_showAdvanced !== null){
1267 } else { //if setShowAdvanced is called without any preference
1268 //make the default to not show advanced elements.
1269 $showadvancedNow = get_user_preferences(
1270 moodle_strtolower($this->_formName.'_showadvanced', 0));
1273 //value of hidden element
1274 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1276 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1277 //toggle if button pressed or else stay the same
1278 if ($hiddenLast == -1) {
1279 $next = $showadvancedNow;
1280 } elseif ($buttonPressed) { //toggle on button press
1281 $next = !$hiddenLast;
1283 $next = $hiddenLast;
1285 $this->_showAdvanced = $next;
1286 if ($showadvancedNow != $next){
1287 set_user_preference($this->_formName.'_showadvanced', $next);
1289 $this->setConstants(array('mform_showadvanced_last'=>$next));
1291 function getShowAdvanced(){
1292 return $this->_showAdvanced;
1297 * Accepts a renderer
1299 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
1303 function accept(&$renderer) {
1304 if (method_exists($renderer, 'setAdvancedElements')){
1305 //check for visible fieldsets where all elements are advanced
1306 //and mark these headers as advanced as well.
1307 //And mark all elements in a advanced header as advanced
1308 $stopFields = $renderer->getStopFieldSetElements();
1310 $lastHeaderAdvanced = false;
1311 $anyAdvanced = false;
1312 foreach (array_keys($this->_elements) as $elementIndex){
1313 $element =& $this->_elements[$elementIndex];
1315 // if closing header and any contained element was advanced then mark it as advanced
1316 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1317 if ($anyAdvanced && !is_null($lastHeader)){
1318 $this->setAdvanced($lastHeader->getName());
1320 $lastHeaderAdvanced = false;
1323 } elseif ($lastHeaderAdvanced) {
1324 $this->setAdvanced($element->getName());
1327 if ($element->getType()=='header'){
1328 $lastHeader =& $element;
1329 $anyAdvanced = false;
1330 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1331 } elseif (isset($this->_advancedElements[$element->getName()])){
1332 $anyAdvanced = true;
1335 // the last header may not be closed yet...
1336 if ($anyAdvanced && !is_null($lastHeader)){
1337 $this->setAdvanced($lastHeader->getName());
1339 $renderer->setAdvancedElements($this->_advancedElements);
1342 parent::accept($renderer);
1346 * @param string $elementName
1348 function closeHeaderBefore($elementName){
1349 $renderer =& $this->defaultRenderer();
1350 $renderer->addStopFieldsetElements($elementName);
1354 * Should be used for all elements of a form except for select, radio and checkboxes which
1355 * clean their own data.
1357 * @param string $elementname
1358 * @param integer $paramtype use the constants PARAM_*.
1359 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1360 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1361 * It will strip all html tags. But will still let tags for multilang support
1363 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1364 * html editor. Data from the editor is later cleaned before display using
1365 * format_text() function. PARAM_RAW can also be used for data that is validated
1366 * by some other way or printed by p() or s().
1367 * * PARAM_INT should be used for integers.
1368 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1371 function setType($elementname, $paramtype) {
1372 $this->_types[$elementname] = $paramtype;
1376 * See description of setType above. This can be used to set several types at once.
1378 * @param array $paramtypes
1380 function setTypes($paramtypes) {
1381 $this->_types = $paramtypes + $this->_types;
1385 * @param array $submission
1386 * @param array $files
1388 function updateSubmission($submission, $files) {
1389 $this->_flagSubmitted = false;
1391 if (empty($submission)) {
1392 $this->_submitValues = array();
1394 foreach ($submission as $key=>$s) {
1395 if (array_key_exists($key, $this->_types)) {
1396 $submission[$key] = clean_param($s, $this->_types[$key]);
1398 $submission[$key] = clean_param($s, PARAM_RAW);
1401 $this->_submitValues = $submission;
1402 $this->_flagSubmitted = true;
1405 if (empty($files)) {
1406 $this->_submitFiles = array();
1408 $this->_submitFiles = $files;
1409 $this->_flagSubmitted = true;
1412 // need to tell all elements that they need to update their value attribute.
1413 foreach (array_keys($this->_elements) as $key) {
1414 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1421 function getReqHTML(){
1422 return $this->_reqHTML;
1428 function getAdvancedHTML(){
1429 return $this->_advancedHTML;
1433 * Initializes a default form value. Used to specify the default for a new entry where
1434 * no data is loaded in using moodleform::set_data()
1436 * note: $slashed param removed
1438 * @param string $elementname element name
1439 * @param mixed $values values for that element name
1443 function setDefault($elementName, $defaultValue){
1444 $this->setDefaults(array($elementName=>$defaultValue));
1445 } // end func setDefault
1447 * Add an array of buttons to the form
1448 * @param array $buttons An associative array representing help button to attach to
1449 * to the form. keys of array correspond to names of elements in form.
1450 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1451 * @param bool $suppresscheck
1452 * @param string $function
1455 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1457 debugging('function moodle_form::setHelpButtons() is deprecated');
1458 //foreach ($buttons as $elementname => $button){
1459 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1463 * Add a single button.
1465 * @deprecated use addHelpButton() instead
1466 * @param string $elementname name of the element to add the item to
1467 * @param array $button arguments to pass to function $function
1468 * @param boolean $suppresscheck whether to throw an error if the element
1470 * @param string $function - function to generate html from the arguments in $button
1471 * @param string $function
1473 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1476 debugging('function moodle_form::setHelpButton() is deprecated');
1477 if ($function !== 'helpbutton') {
1478 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1481 $buttonargs = (array)$buttonargs;
1483 if (array_key_exists($elementname, $this->_elementIndex)) {
1484 //_elements has a numeric index, this code accesses the elements by name
1485 $element = $this->_elements[$this->_elementIndex[$elementname]];
1487 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1488 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1489 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1490 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1492 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1494 } else if (!$suppresscheck) {
1495 print_error('nonexistentformelements', 'form', '', $elementname);
1500 * Add a help button to element, only one button per element is allowed.
1502 * This is new, simplified and preferable method of setting a help icon on form elements.
1503 * It uses the new $OUTPUT->help_icon().
1505 * Typically, you will provide the same identifier and the component as you have used for the
1506 * label of the element. The string identifier with the _help suffix added is then used
1507 * as the help string.
1509 * There has to be two strings defined:
1510 * 1/ get_string($identifier, $component) - the title of the help page
1511 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1514 * @param string $elementname name of the element to add the item to
1515 * @param string $identifier help string identifier without _help suffix
1516 * @param string $component component name to look the help string in
1517 * @param string $linktext optional text to display next to the icon
1518 * @param boolean $suppresscheck set to true if the element may not exist
1521 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1523 if (array_key_exists($elementname, $this->_elementIndex)) {
1524 $element = $this->_elements[$this->_elementIndex[$elementname]];
1525 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1526 } else if (!$suppresscheck) {
1527 debugging(get_string('nonexistentformelements', 'form', $elementname));
1532 * Set constant value not overridden by _POST or _GET
1533 * note: this does not work for complex names with [] :-(
1535 * @param string $elname name of element
1536 * @param mixed $value
1539 function setConstant($elname, $value) {
1540 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1541 $element =& $this->getElement($elname);
1542 $element->onQuickFormEvent('updateValue', null, $this);
1546 * @param string $elementList
1548 function exportValues($elementList = null){
1549 $unfiltered = array();
1550 if (null === $elementList) {
1551 // iterate over all elements, calling their exportValue() methods
1552 $emptyarray = array();
1553 foreach (array_keys($this->_elements) as $key) {
1554 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1555 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1557 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1560 if (is_array($value)) {
1561 // This shit throws a bogus warning in PHP 4.3.x
1562 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1566 if (!is_array($elementList)) {
1567 $elementList = array_map('trim', explode(',', $elementList));
1569 foreach ($elementList as $elementName) {
1570 $value = $this->exportValue($elementName);
1571 if (PEAR::isError($value)) {
1574 //oh, stock QuickFOrm was returning array of arrays!
1575 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1582 * Adds a validation rule for the given field
1584 * If the element is in fact a group, it will be considered as a whole.
1585 * To validate grouped elements as separated entities,
1586 * use addGroupRule instead of addRule.
1588 * @param string $element Form element name
1589 * @param string $message Message to display for invalid data
1590 * @param string $type Rule type, use getRegisteredRules() to get types
1591 * @param string $format (optional)Required for extra rule data
1592 * @param string $validation (optional)Where to perform validation: "server", "client"
1593 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1594 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1597 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1599 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1600 if ($validation == 'client') {
1601 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1604 } // end func addRule
1606 * Adds a validation rule for the given group of elements
1608 * Only groups with a name can be assigned a validation rule
1609 * Use addGroupRule when you need to validate elements inside the group.
1610 * Use addRule if you need to validate the group as a whole. In this case,
1611 * the same rule will be applied to all elements in the group.
1612 * Use addRule if you need to validate the group against a function.
1614 * @param string $group Form group name
1615 * @param mixed $arg1 Array for multiple elements or error message string for one element
1616 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1617 * @param string $format (optional)Required for extra rule data
1618 * @param int $howmany (optional)How many valid elements should be in the group
1619 * @param string $validation (optional)Where to perform validation: "server", "client"
1620 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1623 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1625 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1626 if (is_array($arg1)) {
1627 foreach ($arg1 as $rules) {
1628 foreach ($rules as $rule) {
1629 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1631 if ('client' == $validation) {
1632 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1636 } elseif (is_string($arg1)) {
1638 if ($validation == 'client') {
1639 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1642 } // end func addGroupRule
1646 * Returns the client side validation script
1648 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1649 * and slightly modified to run rules per-element
1650 * Needed to override this because of an error with client side validation of grouped elements.
1653 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1655 function getValidationScript()
1657 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1661 include_once('HTML/QuickForm/RuleRegistry.php');
1662 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1673 foreach ($this->_rules as $elementName => $rules) {
1674 foreach ($rules as $rule) {
1675 if ('client' == $rule['validation']) {
1676 unset($element); //TODO: find out how to properly initialize it
1678 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1679 $rule['message'] = strtr($rule['message'], $js_escape);
1681 if (isset($rule['group'])) {
1682 $group =& $this->getElement($rule['group']);
1683 // No JavaScript validation for frozen elements
1684 if ($group->isFrozen()) {
1687 $elements =& $group->getElements();
1688 foreach (array_keys($elements) as $key) {
1689 if ($elementName == $group->getElementName($key)) {
1690 $element =& $elements[$key];
1694 } elseif ($dependent) {
1696 $element[] =& $this->getElement($elementName);
1697 foreach ($rule['dependent'] as $elName) {
1698 $element[] =& $this->getElement($elName);
1701 $element =& $this->getElement($elementName);
1703 // No JavaScript validation for frozen elements
1704 if (is_object($element) && $element->isFrozen()) {
1706 } elseif (is_array($element)) {
1707 foreach (array_keys($element) as $key) {
1708 if ($element[$key]->isFrozen()) {
1713 // Fix for bug displaying errors for elements in a group
1714 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1715 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1716 $test[$elementName][1]=$element;
1722 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1723 // the form, and then that form field gets corrupted by the code that follows.
1727 <script type="text/javascript">
1730 var skipClientValidation = false;
1732 function qf_errorHandler(element, _qfMsg) {
1733 div = element.parentNode;
1735 if ((div == undefined) || (element.name == undefined)) {
1736 //no checking can be done for undefined elements so let server handle it.
1740 if (_qfMsg != \'\') {
1741 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1743 errorSpan = document.createElement("span");
1744 errorSpan.id = \'id_error_\'+element.name;
1745 errorSpan.className = "error";
1746 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1749 while (errorSpan.firstChild) {
1750 errorSpan.removeChild(errorSpan.firstChild);
1753 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1754 errorSpan.appendChild(document.createElement("br"));
1756 if (div.className.substr(div.className.length - 6, 6) != " error"
1757 && div.className != "error") {
1758 div.className += " error";
1763 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1765 errorSpan.parentNode.removeChild(errorSpan);
1768 if (div.className.substr(div.className.length - 6, 6) == " error") {
1769 div.className = div.className.substr(0, div.className.length - 6);
1770 } else if (div.className == "error") {
1778 foreach ($test as $elementName => $jsandelement) {
1779 // Fix for bug displaying errors for elements in a group
1781 list($jsArr,$element)=$jsandelement;
1783 $escapedElementName = preg_replace_callback(
1785 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1788 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1789 if (undefined == element) {
1790 //required element was not found, then let form be submitted without client side validation
1794 var errFlag = new Array();
1797 var frm = element.parentNode;
1798 if ((undefined != element.name) && (frm != undefined)) {
1799 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1800 frm = frm.parentNode;
1802 ' . join("\n", $jsArr) . '
1803 return qf_errorHandler(element, _qfMsg);
1805 //element name should be defined else error msg will not be displayed.
1811 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1812 if (!ret && !first_focus) {
1814 frm.elements[\''.$elementName.'\'].focus();
1818 // Fix for bug displaying errors for elements in a group
1820 //$element =& $this->getElement($elementName);
1822 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1823 $onBlur = $element->getAttribute('onBlur');
1824 $onChange = $element->getAttribute('onChange');
1825 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1826 'onChange' => $onChange . $valFunc));
1828 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1830 function validate_' . $this->_formName . '(frm) {
1831 if (skipClientValidation) {
1836 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1837 var first_focus = false;
1838 ' . $validateJS . ';
1844 } // end func getValidationScript
1845 function _setDefaultRuleMessages(){
1846 foreach ($this->_rules as $field => $rulesarr){
1847 foreach ($rulesarr as $key => $rule){
1848 if ($rule['message']===null){
1850 $a->format=$rule['format'];
1851 $str=get_string('err_'.$rule['type'], 'form', $a);
1852 if (strpos($str, '[[')!==0){
1853 $this->_rules[$field][$key]['message']=$str;
1860 function getLockOptionObject(){
1862 foreach ($this->_dependencies as $dependentOn => $conditions){
1863 $result[$dependentOn] = array();
1864 foreach ($conditions as $condition=>$values) {
1865 $result[$dependentOn][$condition] = array();
1866 foreach ($values as $value=>$dependents) {
1867 $result[$dependentOn][$condition][$value] = array();
1869 foreach ($dependents as $dependent) {
1870 $elements = $this->_getElNamesRecursive($dependent);
1871 if (empty($elements)) {
1872 // probably element inside of some group
1873 $elements = array($dependent);
1875 foreach($elements as $element) {
1876 if ($element == $dependentOn) {
1879 $result[$dependentOn][$condition][$value][] = $element;
1885 return array($this->getAttribute('id'), $result);
1889 * @param mixed $element
1892 function _getElNamesRecursive($element) {
1893 if (is_string($element)) {
1894 if (!$this->elementExists($element)) {
1897 $element = $this->getElement($element);
1900 if (is_a($element, 'HTML_QuickForm_group')) {
1901 $elsInGroup = $element->getElements();
1903 foreach ($elsInGroup as $elInGroup){
1904 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1905 // not sure if this would work - groups nested in groups
1906 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1908 $elNames[] = $element->getElementName($elInGroup->getName());
1912 } else if (is_a($element, 'HTML_QuickForm_header')) {
1915 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1918 } else if (method_exists($element, 'getPrivateName')) {
1919 return array($element->getPrivateName());
1922 $elNames = array($element->getName());
1929 * Adds a dependency for $elementName which will be disabled if $condition is met.
1930 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1931 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1932 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1933 * of the $dependentOn element is $condition (such as equal) to $value.
1935 * @param string $elementName the name of the element which will be disabled
1936 * @param string $dependentOn the name of the element whose state will be checked for
1938 * @param string $condition the condition to check
1939 * @param mixed $value used in conjunction with condition.
1941 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1942 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1943 $this->_dependencies[$dependentOn] = array();
1945 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1946 $this->_dependencies[$dependentOn][$condition] = array();
1948 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1949 $this->_dependencies[$dependentOn][$condition][$value] = array();
1951 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1954 function registerNoSubmitButton($buttonname){
1955 $this->_noSubmitButtons[]=$buttonname;
1959 * @param string $buttonname
1962 function isNoSubmitButton($buttonname){
1963 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1967 * @param string $buttonname
1969 function _registerCancelButton($addfieldsname){
1970 $this->_cancelButtons[]=$addfieldsname;
1973 * Displays elements without HTML input tags.
1974 * This method is different to freeze() in that it makes sure no hidden
1975 * elements are included in the form.
1976 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1978 * This function also removes all previously defined rules.
1980 * @param mixed $elementList array or string of element(s) to be frozen
1983 function hardFreeze($elementList=null)
1985 if (!isset($elementList)) {
1986 $this->_freezeAll = true;
1987 $elementList = array();
1989 if (!is_array($elementList)) {
1990 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1992 $elementList = array_flip($elementList);
1995 foreach (array_keys($this->_elements) as $key) {
1996 $name = $this->_elements[$key]->getName();
1997 if ($this->_freezeAll || isset($elementList[$name])) {
1998 $this->_elements[$key]->freeze();
1999 $this->_elements[$key]->setPersistantFreeze(false);
2000 unset($elementList[$name]);
2003 $this->_rules[$name] = array();
2004 // if field is required, remove the rule
2005 $unset = array_search($name, $this->_required);
2006 if ($unset !== false) {
2007 unset($this->_required[$unset]);
2012 if (!empty($elementList)) {
2013 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);
2018 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2020 * This function also removes all previously defined rules of elements it freezes.
2022 * throws HTML_QuickForm_Error
2024 * @param array $elementList array or string of element(s) not to be frozen
2027 function hardFreezeAllVisibleExcept($elementList)
2029 $elementList = array_flip($elementList);
2030 foreach (array_keys($this->_elements) as $key) {
2031 $name = $this->_elements[$key]->getName();
2032 $type = $this->_elements[$key]->getType();
2034 if ($type == 'hidden'){
2035 // leave hidden types as they are
2036 } elseif (!isset($elementList[$name])) {
2037 $this->_elements[$key]->freeze();
2038 $this->_elements[$key]->setPersistantFreeze(false);
2041 $this->_rules[$name] = array();
2042 // if field is required, remove the rule
2043 $unset = array_search($name, $this->_required);
2044 if ($unset !== false) {
2045 unset($this->_required[$unset]);
2052 * Tells whether the form was already submitted
2054 * This is useful since the _submitFiles and _submitValues arrays
2055 * may be completely empty after the trackSubmit value is removed.
2060 function isSubmitted()
2062 return parent::isSubmitted() && (!$this->isFrozen());
2068 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2069 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2071 * Stylesheet is part of standard theme and should be automatically included.
2073 * @package moodlecore
2074 * @copyright Jamie Pratt <me@jamiep.org>
2075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2077 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2080 * Element template array
2084 var $_elementTemplates;
2086 * Template used when opening a hidden fieldset
2087 * (i.e. a fieldset that is opened when there is no header element)
2091 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2093 * Header Template string
2097 var $_headerTemplate =
2098 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2101 * Template used when opening a fieldset
2105 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2108 * Template used when closing a fieldset
2112 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2115 * Required Note template string
2119 var $_requiredNoteTemplate =
2120 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2122 var $_advancedElements = array();
2125 * Whether to display advanced elements (on page load)
2127 * @var integer 1 means show 0 means hide
2131 function MoodleQuickForm_Renderer(){
2132 // switch next two lines for ol li containers for form items.
2133 // $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>');
2134 $this->_elementTemplates = array(
2135 '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>',
2137 '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>',
2139 '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} </div></div>',
2141 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2145 parent::HTML_QuickForm_Renderer_Tableless();
2149 * @param array $elements
2151 function setAdvancedElements($elements){
2152 $this->_advancedElements = $elements;
2156 * What to do when starting the form
2158 * @param object $form MoodleQuickForm
2160 function startForm(&$form){
2161 $this->_reqHTML = $form->getReqHTML();
2162 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2163 $this->_advancedHTML = $form->getAdvancedHTML();
2164 $this->_showAdvanced = $form->getShowAdvanced();
2165 parent::startForm($form);
2166 if ($form->isFrozen()){
2167 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2169 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2170 $this->_hiddenHtml .= $form->_pageparams;
2177 * @param object $group Passed by reference
2178 * @param mixed $required
2179 * @param mixed $error
2181 function startGroup(&$group, $required, $error){
2182 if (method_exists($group, 'getElementTemplateType')){
2183 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2185 $html = $this->_elementTemplates['default'];
2188 if ($this->_showAdvanced){
2189 $advclass = ' advanced';
2191 $advclass = ' advanced hide';
2193 if (isset($this->_advancedElements[$group->getName()])){
2194 $html =str_replace(' {advanced}', $advclass, $html);
2195 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2197 $html =str_replace(' {advanced}', '', $html);
2198 $html =str_replace('{advancedimg}', '', $html);
2200 if (method_exists($group, 'getHelpButton')){
2201 $html =str_replace('{help}', $group->getHelpButton(), $html);
2203 $html =str_replace('{help}', '', $html);
2205 $html =str_replace('{name}', $group->getName(), $html);
2206 $html =str_replace('{type}', 'fgroup', $html);
2208 $this->_templates[$group->getName()]=$html;
2209 // Fix for bug in tableless quickforms that didn't allow you to stop a
2210 // fieldset before a group of elements.
2211 // if the element name indicates the end of a fieldset, close the fieldset
2212 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2213 && $this->_fieldsetsOpen > 0
2215 $this->_html .= $this->_closeFieldsetTemplate;
2216 $this->_fieldsetsOpen--;
2218 parent::startGroup($group, $required, $error);
2221 * @param object $element
2222 * @param mixed $required
2223 * @param mixed $error
2225 function renderElement(&$element, $required, $error){
2226 //manipulate id of all elements before rendering
2227 if (!is_null($element->getAttribute('id'))) {
2228 $id = $element->getAttribute('id');
2230 $id = $element->getName();
2232 //strip qf_ prefix and replace '[' with '_' and strip ']'
2233 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
2234 if (strpos($id, 'id_') !== 0){
2235 $element->updateAttributes(array('id'=>'id_'.$id));
2238 //adding stuff to place holders in template
2239 //check if this is a group element first
2240 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2241 // so it gets substitutions for *each* element
2242 $html = $this->_groupElementTemplate;
2244 elseif (method_exists($element, 'getElementTemplateType')){
2245 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2247 $html = $this->_elementTemplates['default'];
2249 if ($this->_showAdvanced){
2250 $advclass = ' advanced';
2252 $advclass = ' advanced hide';
2254 if (isset($this->_advancedElements[$element->getName()])){
2255 $html =str_replace(' {advanced}', $advclass, $html);
2257 $html =str_replace(' {advanced}', '', $html);
2259 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2260 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2262 $html =str_replace('{advancedimg}', '', $html);
2264 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2265 $html =str_replace('{name}', $element->getName(), $html);
2266 if (method_exists($element, 'getHelpButton')){
2267 $html = str_replace('{help}', $element->getHelpButton(), $html);
2269 $html = str_replace('{help}', '', $html);
2272 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2273 $this->_groupElementTemplate = $html;
2275 elseif (!isset($this->_templates[$element->getName()])) {
2276 $this->_templates[$element->getName()] = $html;
2279 parent::renderElement($element, $required, $error);
2283 * @global moodle_page $PAGE
2284 * @param object $form Passed by reference
2286 function finishForm(&$form){
2288 if ($form->isFrozen()){
2289 $this->_hiddenHtml = '';
2291 parent::finishForm($form);
2292 if (!$form->isFrozen()) {
2293 $args = $form->getLockOptionObject();
2294 if (count($args[1]) > 0) {
2295 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, false, moodleform::get_js_module());
2300 * Called when visiting a header element
2302 * @param object $header An HTML_QuickForm_header element being visited
2305 * @global moodle_page $PAGE
2307 function renderHeader(&$header) {
2310 $name = $header->getName();
2312 $id = empty($name) ? '' : ' id="' . $name . '"';
2313 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2314 if (is_null($header->_text)) {
2316 } elseif (!empty($name) && isset($this->_templates[$name])) {
2317 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2319 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2322 if (isset($this->_advancedElements[$name])){
2323 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2324 $elementName='mform_showadvanced';
2325 if ($this->_showAdvanced==0){
2326 $buttonlabel = get_string('showadvanced', 'form');
2328 $buttonlabel = get_string('hideadvanced', 'form');
2330 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2331 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2332 $header_html = str_replace('{button}', $button, $header_html);
2334 $header_html =str_replace('{advancedimg}', '', $header_html);
2335 $header_html = str_replace('{button}', '', $header_html);
2338 if ($this->_fieldsetsOpen > 0) {
2339 $this->_html .= $this->_closeFieldsetTemplate;
2340 $this->_fieldsetsOpen--;
2343 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2344 if ($this->_showAdvanced){
2345 $advclass = ' class="advanced"';
2347 $advclass = ' class="advanced hide"';
2349 if (isset($this->_advancedElements[$name])){
2350 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2352 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2354 $this->_html .= $openFieldsetTemplate . $header_html;
2355 $this->_fieldsetsOpen++;
2356 } // end func renderHeader
2358 function getStopFieldsetElements(){
2359 return $this->_stopFieldsetElements;
2364 * Required elements validation
2365 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2367 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2369 * Checks if an element is not empty.
2370 * This is a server-side validation, it works for both text fields and editor fields
2372 * @param string $value Value to check
2373 * @param mixed $options Not used yet
2374 * @return boolean true if value is not empty
2376 function validate($value, $options = null) {
2378 if (is_array($value) && array_key_exists('text', $value)) {
2379 $value = $value['text'];
2381 $stripvalues = array(
2382 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2383 '#(\xc2|\xa0|\s| )#', //any whitespaces actually
2385 if (!empty($CFG->strictformsrequired)) {
2386 $value = preg_replace($stripvalues, '', (string)$value);
2388 if ((string)$value == '') {
2395 * This function returns Javascript code used to build client-side validation.
2396 * It checks if an element is not empty.
2397 * Note, that QuickForm does not know how to work with editor text field and builds not correct
2398 * JS code for validation. If client check is enabled for editor field it will not be validated
2399 * on client side no matter what this function returns.
2401 * @param mixed $options Not used yet
2404 function getValidationScript($options = null) {
2406 if (!empty($CFG->strictformsrequired)) {
2407 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2409 return array('', "{jsVar} == ''");
2415 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2416 * @name $_HTML_QuickForm_default_renderer
2418 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2420 /** Please keep this list in alphabetical order. */
2421 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2422 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2423 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2424 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2425 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2426 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2427 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2428 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2429 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2430 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2431 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2432 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2433 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2434 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2435 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2436 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2437 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2438 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2439 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2440 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2441 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2442 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2443 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2444 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2445 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2446 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2447 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2448 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2449 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2450 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2451 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2452 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2453 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2454 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2455 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2456 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2458 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");