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 defintion 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
39 /** setup.php icludes our hacked pear libs first */
40 require_once 'HTML/QuickForm.php';
41 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
42 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once $CFG->libdir.'/filelib.php';
45 require_once $CFG->libdir.'/uploadlib.php'; // TODO: remove
47 define('EDITOR_UNLIMITED_FILES', -1);
50 * Callback called when PEAR throws an error
52 * @param PEAR_Error $error
54 function pear_handle_error($error){
55 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
56 echo '<br /> <strong>Backtrace </strong>:';
57 print_object($error->backtrace);
60 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
61 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
66 * @staticvar bool $done
68 function form_init_date_js() {
72 $PAGE->requires->yui2_lib('calendar');
73 $PAGE->requires->yui2_lib('container');
74 $PAGE->requires->js_function_call('init_date_selectors',
75 array(get_string('firstdayofweek')));
81 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
82 * use this class you should write a class definition which extends this class or a more specific
83 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
85 * You will write your own definition() method which performs the form set up.
88 * @copyright Jamie Pratt <me@jamiep.org>
89 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
91 abstract class moodleform {
93 protected $_formname; // form name
95 * quickform object definition
97 * @var object MoodleQuickForm
105 protected $_customdata;
107 * definition_after_data executed flag
108 * @var object definition_finalized
110 protected $_definition_finalized = false;
113 * The constructor function calls the abstract function definition() and it will then
114 * process and clean and attempt to validate incoming data.
116 * It will call your custom validate method to validate data and will also check any rules
117 * you have specified in definition using addRule
119 * The name of the form (id attribute of the form) is automatically generated depending on
120 * the name you gave the class extending moodleform. You should call your class something
123 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
124 * current url. If a moodle_url object then outputs params as hidden variables.
125 * @param array $customdata if your form defintion method needs access to data such as $course
126 * $cm, etc. to construct the form definition then pass it in this array. You can
127 * use globals for somethings.
128 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
129 * be merged and used as incoming data to the form.
130 * @param string $target target frame for form submission. You will rarely use this. Don't use
131 * it if you don't need to as the target attribute is deprecated in xhtml
133 * @param mixed $attributes you can pass a string of html attributes here or an array.
134 * @param bool $editable
135 * @return object moodleform
137 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
139 $action = strip_querystring(qualified_me());
142 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
143 $this->_customdata = $customdata;
144 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
146 $this->_form->hardFreeze();
151 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
152 $this->_form->setType('sesskey', PARAM_RAW);
153 $this->_form->setDefault('sesskey', sesskey());
154 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
155 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
156 $this->_form->setDefault('_qf__'.$this->_formname, 1);
157 $this->_form->_setDefaultRuleMessages();
159 // we have to know all input types before processing submission ;-)
160 $this->_process_submission($method);
164 * To autofocus on first form element or first element with error.
166 * @param string $name if this is set then the focus is forced to a field with this name
168 * @return string javascript to select form element with first error or
169 * first element if no errors. Use this as a parameter
170 * when calling print_header
172 function focus($name=NULL) {
173 $form =& $this->_form;
174 $elkeys = array_keys($form->_elementIndex);
176 if (isset($form->_errors) && 0 != count($form->_errors)){
177 $errorkeys = array_keys($form->_errors);
178 $elkeys = array_intersect($elkeys, $errorkeys);
182 if ($error or empty($name)) {
184 while (empty($names) and !empty($elkeys)) {
185 $el = array_shift($elkeys);
186 $names = $form->_getElNamesRecursive($el);
188 if (!empty($names)) {
189 $name = array_shift($names);
195 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
202 * Internal method. Alters submitted data to be suitable for quickforms processing.
203 * Must be called when the form is fully set up.
205 * @param string $method
207 function _process_submission($method) {
208 $submission = array();
209 if ($method == 'post') {
210 if (!empty($_POST)) {
211 $submission = $_POST;
214 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
217 // following trick is needed to enable proper sesskey checks when using GET forms
218 // the _qf__.$this->_formname serves as a marker that form was actually submitted
219 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
220 if (!confirm_sesskey()) {
221 print_error('invalidsesskey');
225 $submission = array();
229 $this->_form->updateSubmission($submission, $files);
233 * Internal method. Validates all old-style uploaded files.
237 * @param array $files
238 * @return bool|array Success or an array of errors
240 function _validate_files(&$files) {
241 global $CFG, $COURSE;
245 if (empty($_FILES)) {
246 // we do not need to do any checks because no files were submitted
247 // note: server side rules do not work for files - use custom verification in validate() instead
252 $filenames = array();
254 // now check that we really want each file
255 foreach ($_FILES as $elname=>$file) {
256 $required = $this->_form->isElementRequired($elname);
258 if ($file['error'] == 4 and $file['size'] == 0) {
260 $errors[$elname] = get_string('required');
262 unset($_FILES[$elname]);
266 if (!empty($file['error'])) {
267 $errors[$elname] = file_get_upload_error($file['error']);
268 unset($_FILES[$elname]);
272 if (!is_uploaded_file($file['tmp_name'])) {
273 // TODO: improve error message
274 $errors[$elname] = get_string('error');
275 unset($_FILES[$elname]);
279 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
280 // hmm, this file was not requested
281 unset($_FILES[$elname]);
286 // TODO: rethink the file scanning
287 if ($CFG->runclamonupload) {
288 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
289 $errors[$elname] = $_FILES[$elname]['uploadlog'];
290 unset($_FILES[$elname]);
295 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
296 if ($filename === '') {
297 // TODO: improve error message - wrong chars
298 $errors[$elname] = get_string('error');
299 unset($_FILES[$elname]);
302 if (in_array($filename, $filenames)) {
303 // TODO: improve error message - duplicate name
304 $errors[$elname] = get_string('error');
305 unset($_FILES[$elname]);
308 $filenames[] = $filename;
309 $_FILES[$elname]['name'] = $filename;
311 $files[$elname] = $_FILES[$elname]['tmp_name'];
314 // return errors if found
315 if (count($errors) == 0){
325 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
326 * form definition (new entry form); this function is used to load in data where values
327 * already exist and data is being edited (edit entry form).
329 * note: $slashed param removed
331 * @param mixed $default_values object or array of default values
332 * @param bool $slased true if magic quotes applied to data values
334 function set_data($default_values) {
335 if (is_object($default_values)) {
336 $default_values = (array)$default_values;
338 $this->_form->setDefaults($default_values);
344 function set_upload_manager($um=false) {
345 debugging('Not used anymore, please fix code!');
349 * Check that form was submitted. Does not check validity of submitted data.
351 * @return bool true if form properly submitted
353 function is_submitted() {
354 return $this->_form->isSubmitted();
358 * @staticvar bool $nosubmit
360 function no_submit_button_pressed(){
361 static $nosubmit = null; // one check is enough
362 if (!is_null($nosubmit)){
365 $mform =& $this->_form;
367 if (!$this->is_submitted()){
370 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
371 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
381 * Check that form data is valid.
382 * You should almost always use this, rather than {@see validate_defined_fields}
384 * @staticvar bool $validated
385 * @return bool true if form data valid
387 function is_validated() {
388 //finalize the form definition before any processing
389 if (!$this->_definition_finalized) {
390 $this->_definition_finalized = true;
391 $this->definition_after_data();
394 return $this->validate_defined_fields();
400 * You almost always want to call {@see is_validated} instead of this
401 * because it calls {@see definition_after_data} first, before validating the form,
402 * which is what you want in 99% of cases.
404 * This is provided as a separate function for those special cases where
405 * you want the form validated before definition_after_data is called
406 * for example, to selectively add new elements depending on a no_submit_button press,
407 * but only when the form is valid when the no_submit_button is pressed,
409 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
410 * is NOT to validate the form when a no submit button has been pressed.
411 * pass true here to override this behaviour
413 * @return bool true if form data valid
415 function validate_defined_fields($validateonnosubmit=false) {
416 static $validated = null; // one validation is enough
417 $mform =& $this->_form;
418 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
420 } elseif ($validated === null) {
421 $internal_val = $mform->validate();
424 $file_val = $this->_validate_files($files);
425 if ($file_val !== true) {
426 if (!empty($file_val)) {
427 foreach ($file_val as $element=>$msg) {
428 $mform->setElementError($element, $msg);
434 $data = $mform->exportValues();
435 $moodle_val = $this->validation($data, $files);
436 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
437 // non-empty array means errors
438 foreach ($moodle_val as $element=>$msg) {
439 $mform->setElementError($element, $msg);
444 // anything else means validation ok
448 $validated = ($internal_val and $moodle_val and $file_val);
454 * Return true if a cancel button has been pressed resulting in the form being submitted.
456 * @return boolean true if a cancel button has been pressed
458 function is_cancelled(){
459 $mform =& $this->_form;
460 if ($mform->isSubmitted()){
461 foreach ($mform->_cancelButtons as $cancelbutton){
462 if (optional_param($cancelbutton, 0, PARAM_RAW)){
471 * Return submitted data if properly submitted or returns NULL if validation fails or
472 * if there is no submitted data.
474 * note: $slashed param removed
476 * @return object submitted data; NULL if not valid or not submitted
478 function get_data() {
479 $mform =& $this->_form;
481 if ($this->is_submitted() and $this->is_validated()) {
482 $data = $mform->exportValues();
483 unset($data['sesskey']); // we do not need to return sesskey
484 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
488 return (object)$data;
496 * Return submitted data without validation or NULL if there is no submitted data.
497 * note: $slashed param removed
499 * @return object submitted data; NULL if not submitted
501 function get_submitted_data() {
502 $mform =& $this->_form;
504 if ($this->is_submitted()) {
505 $data = $mform->exportValues();
506 unset($data['sesskey']); // we do not need to return sesskey
507 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
511 return (object)$data;
519 * Save verified uploaded files into directory. Upload process can be customised from definition()
520 * NOTE: please use save_stored_file() or save_file()
522 * @return bool Always false
524 function save_files($destination) {
525 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
530 * Returns name of uploaded file.
533 * @param string $elname, first element if null
534 * @return mixed false in case of failure, string if ok
536 function get_new_filename($elname=null) {
539 if (!$this->is_submitted() or !$this->is_validated()) {
543 if (is_null($elname)) {
544 if (empty($_FILES)) {
548 $elname = key($_FILES);
551 if (empty($elname)) {
555 $element = $this->_form->getElement($elname);
557 if ($element instanceof MoodleQuickForm_filepicker) {
558 $values = $this->_form->exportValues($elname);
559 if (empty($values[$elname])) {
562 $draftid = $values[$elname];
563 $fs = get_file_storage();
564 $context = get_context_instance(CONTEXT_USER, $USER->id);
565 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
568 $file = reset($files);
569 return $file->get_filename();
572 if (!isset($_FILES[$elname])) {
576 return $_FILES[$elname]['name'];
580 * Save file to standard filesystem
583 * @param string $elname name of element
584 * @param string $pathname full path name of file
585 * @param bool $override override file if exists
586 * @return bool success
588 function save_file($elname, $pathname, $override=false) {
591 if (!$this->is_submitted() or !$this->is_validated()) {
595 if (file_exists($pathname)) {
597 if (!@unlink($pathname)) {
605 $element = $this->_form->getElement($elname);
607 if ($element instanceof MoodleQuickForm_filepicker) {
608 $values = $this->_form->exportValues($elname);
609 if (empty($values[$elname])) {
612 $draftid = $values[$elname];
613 $fs = get_file_storage();
614 $context = get_context_instance(CONTEXT_USER, $USER->id);
615 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
618 $file = reset($files);
620 return $file->copy_content_to($pathname);
622 } else if (isset($_FILES[$elname])) {
623 return copy($_FILES[$elname]['tmp_name'], $pathname);
630 * Save file to local filesystem pool
633 * @param string $elname name of element
634 * @param int $newcontextid
635 * @param string $newfilearea
636 * @param string $newfilepath
637 * @param string $newfilename - use specified filename, if not specified name of uploaded file used
638 * @param bool $overwrite - overwrite file if exists
639 * @param int $newuserid - new userid if required
640 * @return mixed stored_file object or false if error; may throw exception if duplicate found
642 function save_stored_file($elname, $newcontextid, $newfilearea, $newitemid, $newfilepath='/',
643 $newfilename=null, $overwrite=false, $newuserid=null) {
646 if (!$this->is_submitted() or !$this->is_validated()) {
650 if (empty($newuserid)) {
651 $newuserid = $USER->id;
654 $element = $this->_form->getElement($elname);
655 $fs = get_file_storage();
657 if ($element instanceof MoodleQuickForm_filepicker) {
658 $values = $this->_form->exportValues($elname);
659 if (empty($values[$elname])) {
662 $draftid = $values[$elname];
663 $context = get_context_instance(CONTEXT_USER, $USER->id);
664 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
667 $file = reset($files);
668 if (is_null($newfilename)) {
669 $newfilename = $file->get_filename();
673 if ($oldfile = $fs->get_file($newcontextid, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
674 if (!$oldfile->delete()) {
680 $file_record = array('contextid'=>$newcontextid, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
681 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
682 return $fs->create_file_from_storedfile($file_record, $file);
684 } else if (isset($_FILES[$elname])) {
685 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
688 if ($oldfile = $fs->get_file($newcontextid, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
689 if (!$oldfile->delete()) {
695 $file_record = array('contextid'=>$newcontextid, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
696 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
697 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
704 * Get content of uploaded file.
707 * @param $element name of file upload element
708 * @return mixed false in case of failure, string if ok
710 function get_file_content($elname) {
713 if (!$this->is_submitted() or !$this->is_validated()) {
717 $element = $this->_form->getElement($elname);
719 if ($element instanceof MoodleQuickForm_filepicker) {
720 $values = $this->_form->exportValues($elname);
721 if (empty($values[$elname])) {
724 $draftid = $values[$elname];
725 $fs = get_file_storage();
726 $context = get_context_instance(CONTEXT_USER, $USER->id);
727 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
730 $file = reset($files);
732 return $file->get_content();
734 } else if (isset($_FILES[$elname])) {
735 return file_get_contents($_FILES[$elname]['tmp_name']);
745 //finalize the form definition if not yet done
746 if (!$this->_definition_finalized) {
747 $this->_definition_finalized = true;
748 $this->definition_after_data();
750 $this->_form->display();
754 * Abstract method - always override!
756 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
758 protected abstract function definition();
761 * Dummy stub method - override if you need to setup the form depending on current
762 * values. This method is called after definition(), data submission and set_data().
763 * All form setup that is dependent on form values should go in here.
765 function definition_after_data(){
769 * Dummy stub method - override if you needed to perform some extra validation.
770 * If there are errors return array of errors ("fieldname"=>"error message"),
771 * otherwise true if ok.
773 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
775 * @param array $data array of ("fieldname"=>value) of submitted data
776 * @param array $files array of uploaded files "element_name"=>tmp_file_path
777 * @return array of "element_name"=>"error_description" if there are errors,
778 * or an empty array if everything is OK (true allowed for backwards compatibility too).
780 function validation($data, $files) {
785 * Method to add a repeating group of elements to a form.
787 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
788 * @param integer $repeats no of times to repeat elements initially
789 * @param array $options Array of options to apply to elements. Array keys are element names.
790 * This is an array of arrays. The second sets of keys are the option types
792 * 'default' - default value is value
793 * 'type' - PARAM_* constant is value
794 * 'helpbutton' - helpbutton params array is value
795 * 'disabledif' - last three moodleform::disabledIf()
796 * params are value as an array
797 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
798 * @param string $addfieldsname name for button to add more fields
799 * @param int $addfieldsno how many fields to add at a time
800 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
801 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
802 * @return int no of repeats of element in this page
804 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
805 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
806 if ($addstring===null){
807 $addstring = get_string('addfields', 'form', $addfieldsno);
809 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
811 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
812 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
813 if (!empty($addfields)){
814 $repeats += $addfieldsno;
816 $mform =& $this->_form;
817 $mform->registerNoSubmitButton($addfieldsname);
818 $mform->addElement('hidden', $repeathiddenname, $repeats);
819 $mform->setType($repeathiddenname, PARAM_INT);
820 //value not to be overridden by submitted value
821 $mform->setConstants(array($repeathiddenname=>$repeats));
822 $namecloned = array();
823 for ($i = 0; $i < $repeats; $i++) {
824 foreach ($elementobjs as $elementobj){
825 $elementclone = fullclone($elementobj);
826 $name = $elementclone->getName();
827 $namecloned[] = $name;
829 $elementclone->setName($name."[$i]");
831 if (is_a($elementclone, 'HTML_QuickForm_header')) {
832 $value = $elementclone->_text;
833 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
836 $value=$elementclone->getLabel();
837 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
841 $mform->addElement($elementclone);
844 for ($i=0; $i<$repeats; $i++) {
845 foreach ($options as $elementname => $elementoptions){
846 $pos=strpos($elementname, '[');
848 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
849 $realelementname .= substr($elementname, $pos+1);
851 $realelementname = $elementname."[$i]";
853 foreach ($elementoptions as $option => $params){
857 $mform->setDefault($realelementname, $params);
860 $mform->setHelpButton($realelementname, $params);
863 foreach ($namecloned as $num => $name){
864 if ($params[0] == $name){
865 $params[0] = $params[0]."[$i]";
869 $params = array_merge(array($realelementname), $params);
870 call_user_func_array(array(&$mform, 'disabledIf'), $params);
873 if (is_string($params)){
874 $params = array(null, $params, null, 'client');
876 $params = array_merge(array($realelementname), $params);
877 call_user_func_array(array(&$mform, 'addRule'), $params);
884 $mform->addElement('submit', $addfieldsname, $addstring);
886 if (!$addbuttoninside) {
887 $mform->closeHeaderBefore($addfieldsname);
894 * Adds a link/button that controls the checked state of a group of checkboxes.
897 * @param int $groupid The id of the group of advcheckboxes this element controls
898 * @param string $buttontext The text of the link. Defaults to "select all/none"
899 * @param array $attributes associative array of HTML attributes
900 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
902 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
905 $text = get_string('selectallornone', 'form');
908 $mform = $this->_form;
909 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
911 if ($select_value == 0 || is_null($select_value)) {
912 $new_select_value = 1;
914 $new_select_value = 0;
917 $mform->addElement('hidden', "checkbox_controller$groupid");
918 $mform->setType("checkbox_controller$groupid", PARAM_INT);
919 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
921 // Locate all checkboxes for this group and set their value, IF the optional param was given
922 if (!is_null($select_value)) {
923 foreach ($this->_form->_elements as $element) {
924 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
925 $mform->setConstants(array($element->getAttribute('name') => $select_value));
930 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
931 $mform->registerNoSubmitButton($checkbox_controller_name);
933 // Prepare Javascript for submit element
934 $js = "\n//<![CDATA[\n";
935 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
937 function html_quickform_toggle_checkboxes(group) {
938 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
939 var newvalue = false;
940 var global = eval('html_quickform_checkboxgroup' + group + ';');
942 eval('html_quickform_checkboxgroup' + group + ' = 0;');
945 eval('html_quickform_checkboxgroup' + group + ' = 1;');
946 newvalue = 'checked';
949 for (i = 0; i < checkboxes.length; i++) {
950 checkboxes[i].checked = newvalue;
954 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
956 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
960 require_once("$CFG->libdir/form/submitlink.php");
961 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
962 $submitlink->_js = $js;
963 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
964 $mform->addElement($submitlink);
965 $mform->setDefault($checkbox_controller_name, $text);
969 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
970 * if you don't want a cancel button in your form. If you have a cancel button make sure you
971 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
972 * get data with get_data().
974 * @param boolean $cancel whether to show cancel button, default true
975 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
977 function add_action_buttons($cancel = true, $submitlabel=null){
978 if (is_null($submitlabel)){
979 $submitlabel = get_string('savechanges');
981 $mform =& $this->_form;
983 //when two elements we need a group
984 $buttonarray=array();
985 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
986 $buttonarray[] = &$mform->createElement('cancel');
987 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
988 $mform->closeHeaderBefore('buttonar');
991 $mform->addElement('submit', 'submitbutton', $submitlabel);
992 $mform->closeHeaderBefore('submitbutton');
998 * You never extend this class directly. The class methods of this class are available from
999 * the private $this->_form property on moodleform and its children. You generally only
1000 * call methods on this class from within abstract methods that you override on moodleform such
1001 * as definition and definition_after_data
1003 * @package moodlecore
1004 * @copyright Jamie Pratt <me@jamiep.org>
1005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1007 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1009 var $_types = array();
1010 var $_dependencies = array();
1012 * Array of buttons that if pressed do not result in the processing of the form.
1016 var $_noSubmitButtons=array();
1018 * Array of buttons that if pressed do not result in the processing of the form.
1022 var $_cancelButtons=array();
1025 * Array whose keys are element names. If the key exists this is a advanced element
1029 var $_advancedElements = array();
1032 * Whether to display advanced elements (on page load)
1036 var $_showAdvanced = null;
1039 * The form name is derrived from the class name of the wrapper minus the trailing form
1040 * It is a name with words joined by underscores whereas the id attribute is words joined by
1045 var $_formName = '';
1048 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1052 var $_pageparams = '';
1055 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1058 * @staticvar int $formcounter
1059 * @param string $formName Form's name.
1060 * @param string $method (optional)Form's method defaults to 'POST'
1061 * @param mixed $action (optional)Form's action - string or moodle_url
1062 * @param string $target (optional)Form's target defaults to none
1063 * @param mixed $attributes (optional)Extra attributes for <form> tag
1066 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1067 global $CFG, $OUTPUT;
1069 static $formcounter = 1;
1071 HTML_Common::HTML_Common($attributes);
1072 $target = empty($target) ? array() : array('target' => $target);
1073 $this->_formName = $formName;
1074 if (is_a($action, 'moodle_url')){
1075 $this->_pageparams = html_writer::input_hidden_params($action);
1076 $action = $action->out_omit_querystring();
1078 $this->_pageparams = '';
1080 //no 'name' atttribute for form in xhtml strict :
1081 $attributes = array('action'=>$action, 'method'=>$method,
1082 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1084 $this->updateAttributes($attributes);
1086 //this is custom stuff for Moodle :
1087 $oldclass= $this->getAttribute('class');
1088 if (!empty($oldclass)){
1089 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1091 $this->updateAttributes(array('class'=>'mform'));
1093 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1094 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1095 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1096 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
1100 * Use this method to indicate an element in a form is an advanced field. If items in a form
1101 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1102 * form so the user can decide whether to display advanced form controls.
1104 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1106 * @param string $elementName group or element name (not the element name of something inside a group).
1107 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1109 function setAdvanced($elementName, $advanced=true){
1111 $this->_advancedElements[$elementName]='';
1112 } elseif (isset($this->_advancedElements[$elementName])) {
1113 unset($this->_advancedElements[$elementName]);
1115 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1116 $this->setShowAdvanced();
1117 $this->registerNoSubmitButton('mform_showadvanced');
1119 $this->addElement('hidden', 'mform_showadvanced_last');
1120 $this->setType('mform_showadvanced_last', PARAM_INT);
1124 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1125 * display advanced elements in the form until 'Show Advanced' is pressed.
1127 * You can get the last state of the form and possibly save it for this user by using
1128 * value 'mform_showadvanced_last' in submitted data.
1130 * @param boolean $showadvancedNow
1132 function setShowAdvanced($showadvancedNow = null){
1133 if ($showadvancedNow === null){
1134 if ($this->_showAdvanced !== null){
1136 } else { //if setShowAdvanced is called without any preference
1137 //make the default to not show advanced elements.
1138 $showadvancedNow = get_user_preferences(
1139 moodle_strtolower($this->_formName.'_showadvanced', 0));
1142 //value of hidden element
1143 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1145 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1146 //toggle if button pressed or else stay the same
1147 if ($hiddenLast == -1) {
1148 $next = $showadvancedNow;
1149 } elseif ($buttonPressed) { //toggle on button press
1150 $next = !$hiddenLast;
1152 $next = $hiddenLast;
1154 $this->_showAdvanced = $next;
1155 if ($showadvancedNow != $next){
1156 set_user_preference($this->_formName.'_showadvanced', $next);
1158 $this->setConstants(array('mform_showadvanced_last'=>$next));
1160 function getShowAdvanced(){
1161 return $this->_showAdvanced;
1166 * Accepts a renderer
1168 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
1172 function accept(&$renderer) {
1173 if (method_exists($renderer, 'setAdvancedElements')){
1174 //check for visible fieldsets where all elements are advanced
1175 //and mark these headers as advanced as well.
1176 //And mark all elements in a advanced header as advanced
1177 $stopFields = $renderer->getStopFieldSetElements();
1179 $lastHeaderAdvanced = false;
1180 $anyAdvanced = false;
1181 foreach (array_keys($this->_elements) as $elementIndex){
1182 $element =& $this->_elements[$elementIndex];
1184 // if closing header and any contained element was advanced then mark it as advanced
1185 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1186 if ($anyAdvanced && !is_null($lastHeader)){
1187 $this->setAdvanced($lastHeader->getName());
1189 $lastHeaderAdvanced = false;
1192 } elseif ($lastHeaderAdvanced) {
1193 $this->setAdvanced($element->getName());
1196 if ($element->getType()=='header'){
1197 $lastHeader =& $element;
1198 $anyAdvanced = false;
1199 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1200 } elseif (isset($this->_advancedElements[$element->getName()])){
1201 $anyAdvanced = true;
1204 // the last header may not be closed yet...
1205 if ($anyAdvanced && !is_null($lastHeader)){
1206 $this->setAdvanced($lastHeader->getName());
1208 $renderer->setAdvancedElements($this->_advancedElements);
1211 parent::accept($renderer);
1215 * @param string $elementName
1217 function closeHeaderBefore($elementName){
1218 $renderer =& $this->defaultRenderer();
1219 $renderer->addStopFieldsetElements($elementName);
1223 * Should be used for all elements of a form except for select, radio and checkboxes which
1224 * clean their own data.
1226 * @param string $elementname
1227 * @param integer $paramtype use the constants PARAM_*.
1228 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1229 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1230 * It will strip all html tags. But will still let tags for multilang support
1232 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1233 * html editor. Data from the editor is later cleaned before display using
1234 * format_text() function. PARAM_RAW can also be used for data that is validated
1235 * by some other way or printed by p() or s().
1236 * * PARAM_INT should be used for integers.
1237 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1240 function setType($elementname, $paramtype) {
1241 $this->_types[$elementname] = $paramtype;
1245 * See description of setType above. This can be used to set several types at once.
1247 * @param array $paramtypes
1249 function setTypes($paramtypes) {
1250 $this->_types = $paramtypes + $this->_types;
1254 * @param array $submission
1255 * @param array $files
1257 function updateSubmission($submission, $files) {
1258 $this->_flagSubmitted = false;
1260 if (empty($submission)) {
1261 $this->_submitValues = array();
1263 foreach ($submission as $key=>$s) {
1264 if (array_key_exists($key, $this->_types)) {
1265 $submission[$key] = clean_param($s, $this->_types[$key]);
1268 $this->_submitValues = $submission;
1269 $this->_flagSubmitted = true;
1272 if (empty($files)) {
1273 $this->_submitFiles = array();
1275 $this->_submitFiles = $files;
1276 $this->_flagSubmitted = true;
1279 // need to tell all elements that they need to update their value attribute.
1280 foreach (array_keys($this->_elements) as $key) {
1281 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1288 function getReqHTML(){
1289 return $this->_reqHTML;
1295 function getAdvancedHTML(){
1296 return $this->_advancedHTML;
1300 * Initializes a default form value. Used to specify the default for a new entry where
1301 * no data is loaded in using moodleform::set_data()
1303 * note: $slashed param removed
1305 * @param string $elementname element name
1306 * @param mixed $values values for that element name
1310 function setDefault($elementName, $defaultValue){
1311 $this->setDefaults(array($elementName=>$defaultValue));
1312 } // end func setDefault
1314 * Add an array of buttons to the form
1315 * @param array $buttons An associative array representing help button to attach to
1316 * to the form. keys of array correspond to names of elements in form.
1317 * @param bool $suppresscheck
1318 * @param string $function
1321 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1323 foreach ($buttons as $elementname => $button){
1324 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1328 * Add a single button.
1330 * @param string $elementname name of the element to add the item to
1331 * @param array $button arguments to pass to function $function
1332 * @param boolean $suppresscheck whether to throw an error if the element
1334 * @param string $function - function to generate html from the arguments in $button
1335 * @param string $function
1337 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1339 if ($function !== 'helpbutton') {
1340 debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1343 $buttonargs = (array)$buttonargs;
1345 if (array_key_exists($elementname, $this->_elementIndex)) {
1346 //_elements has a numeric index, this code accesses the elements by name
1347 $element = $this->_elements[$this->_elementIndex[$elementname]];
1349 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1350 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1351 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1352 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1354 $element->_helpbutton = $OUTPUT->help_icon($page, $text, $module, $linktext);
1356 } else if (!$suppresscheck) {
1357 print_error('nonexistentformelements', 'form', '', $elementname);
1362 * Set constant value not overriden by _POST or _GET
1363 * note: this does not work for complex names with [] :-(
1365 * @param string $elname name of element
1366 * @param mixed $value
1369 function setConstant($elname, $value) {
1370 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1371 $element =& $this->getElement($elname);
1372 $element->onQuickFormEvent('updateValue', null, $this);
1376 * @param string $elementList
1378 function exportValues($elementList = null){
1379 $unfiltered = array();
1380 if (null === $elementList) {
1381 // iterate over all elements, calling their exportValue() methods
1382 $emptyarray = array();
1383 foreach (array_keys($this->_elements) as $key) {
1384 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1385 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1387 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1390 if (is_array($value)) {
1391 // This shit throws a bogus warning in PHP 4.3.x
1392 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1396 if (!is_array($elementList)) {
1397 $elementList = array_map('trim', explode(',', $elementList));
1399 foreach ($elementList as $elementName) {
1400 $value = $this->exportValue($elementName);
1401 if (PEAR::isError($value)) {
1404 //oh, stock QuickFOrm was returning array of arrays!
1405 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1412 * Adds a validation rule for the given field
1414 * If the element is in fact a group, it will be considered as a whole.
1415 * To validate grouped elements as separated entities,
1416 * use addGroupRule instead of addRule.
1418 * @param string $element Form element name
1419 * @param string $message Message to display for invalid data
1420 * @param string $type Rule type, use getRegisteredRules() to get types
1421 * @param string $format (optional)Required for extra rule data
1422 * @param string $validation (optional)Where to perform validation: "server", "client"
1423 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1424 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1427 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1429 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1430 if ($validation == 'client') {
1431 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1434 } // end func addRule
1436 * Adds a validation rule for the given group of elements
1438 * Only groups with a name can be assigned a validation rule
1439 * Use addGroupRule when you need to validate elements inside the group.
1440 * Use addRule if you need to validate the group as a whole. In this case,
1441 * the same rule will be applied to all elements in the group.
1442 * Use addRule if you need to validate the group against a function.
1444 * @param string $group Form group name
1445 * @param mixed $arg1 Array for multiple elements or error message string for one element
1446 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1447 * @param string $format (optional)Required for extra rule data
1448 * @param int $howmany (optional)How many valid elements should be in the group
1449 * @param string $validation (optional)Where to perform validation: "server", "client"
1450 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1453 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1455 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1456 if (is_array($arg1)) {
1457 foreach ($arg1 as $rules) {
1458 foreach ($rules as $rule) {
1459 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1461 if ('client' == $validation) {
1462 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1466 } elseif (is_string($arg1)) {
1468 if ($validation == 'client') {
1469 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1472 } // end func addGroupRule
1476 * Returns the client side validation script
1478 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1479 * and slightly modified to run rules per-element
1480 * Needed to override this because of an error with client side validation of grouped elements.
1483 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1485 function getValidationScript()
1487 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1491 include_once('HTML/QuickForm/RuleRegistry.php');
1492 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1503 foreach ($this->_rules as $elementName => $rules) {
1504 foreach ($rules as $rule) {
1505 if ('client' == $rule['validation']) {
1506 unset($element); //TODO: find out how to properly initialize it
1508 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1509 $rule['message'] = strtr($rule['message'], $js_escape);
1511 if (isset($rule['group'])) {
1512 $group =& $this->getElement($rule['group']);
1513 // No JavaScript validation for frozen elements
1514 if ($group->isFrozen()) {
1517 $elements =& $group->getElements();
1518 foreach (array_keys($elements) as $key) {
1519 if ($elementName == $group->getElementName($key)) {
1520 $element =& $elements[$key];
1524 } elseif ($dependent) {
1526 $element[] =& $this->getElement($elementName);
1527 foreach ($rule['dependent'] as $elName) {
1528 $element[] =& $this->getElement($elName);
1531 $element =& $this->getElement($elementName);
1533 // No JavaScript validation for frozen elements
1534 if (is_object($element) && $element->isFrozen()) {
1536 } elseif (is_array($element)) {
1537 foreach (array_keys($element) as $key) {
1538 if ($element[$key]->isFrozen()) {
1543 // Fix for bug displaying errors for elements in a group
1544 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1545 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1546 $test[$elementName][1]=$element;
1552 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1553 // the form, and then that form field gets corrupted by the code that follows.
1557 <script type="text/javascript">
1560 var skipClientValidation = false;
1562 function qf_errorHandler(element, _qfMsg) {
1563 div = element.parentNode;
1564 if (_qfMsg != \'\') {
1565 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1567 errorSpan = document.createElement("span");
1568 errorSpan.id = \'id_error_\'+element.name;
1569 errorSpan.className = "error";
1570 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1573 while (errorSpan.firstChild) {
1574 errorSpan.removeChild(errorSpan.firstChild);
1577 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1578 errorSpan.appendChild(document.createElement("br"));
1580 if (div.className.substr(div.className.length - 6, 6) != " error"
1581 && div.className != "error") {
1582 div.className += " error";
1587 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1589 errorSpan.parentNode.removeChild(errorSpan);
1592 if (div.className.substr(div.className.length - 6, 6) == " error") {
1593 div.className = div.className.substr(0, div.className.length - 6);
1594 } else if (div.className == "error") {
1602 foreach ($test as $elementName => $jsandelement) {
1603 // Fix for bug displaying errors for elements in a group
1605 list($jsArr,$element)=$jsandelement;
1608 function validate_' . $this->_formName . '_' . $elementName . '(element) {
1610 var errFlag = new Array();
1613 var frm = element.parentNode;
1614 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1615 frm = frm.parentNode;
1617 ' . join("\n", $jsArr) . '
1618 return qf_errorHandler(element, _qfMsg);
1622 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1623 if (!ret && !first_focus) {
1625 frm.elements[\''.$elementName.'\'].focus();
1629 // Fix for bug displaying errors for elements in a group
1631 //$element =& $this->getElement($elementName);
1633 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
1634 $onBlur = $element->getAttribute('onBlur');
1635 $onChange = $element->getAttribute('onChange');
1636 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1637 'onChange' => $onChange . $valFunc));
1639 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1641 function validate_' . $this->_formName . '(frm) {
1642 if (skipClientValidation) {
1647 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1648 var first_focus = false;
1649 ' . $validateJS . ';
1655 } // end func getValidationScript
1656 function _setDefaultRuleMessages(){
1657 foreach ($this->_rules as $field => $rulesarr){
1658 foreach ($rulesarr as $key => $rule){
1659 if ($rule['message']===null){
1661 $a->format=$rule['format'];
1662 $str=get_string('err_'.$rule['type'], 'form', $a);
1663 if (strpos($str, '[[')!==0){
1664 $this->_rules[$field][$key]['message']=$str;
1674 function getLockOptionEndScript(){
1676 $iname = $this->getAttribute('id').'items';
1677 $js = '<script type="text/javascript">'."\n";
1678 $js .= '//<![CDATA['."\n";
1679 $js .= "var $iname = Array();\n";
1681 foreach ($this->_dependencies as $dependentOn => $conditions){
1682 $js .= "{$iname}['$dependentOn'] = Array();\n";
1683 foreach ($conditions as $condition=>$values) {
1684 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1685 foreach ($values as $value=>$dependents) {
1686 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1688 foreach ($dependents as $dependent) {
1689 $elements = $this->_getElNamesRecursive($dependent);
1690 if (empty($elements)) {
1691 // probably element inside of some group
1692 $elements = array($dependent);
1694 foreach($elements as $element) {
1695 if ($element == $dependentOn) {
1698 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1705 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1707 $js .='</script>'."\n";
1712 * @param mixed $element
1715 function _getElNamesRecursive($element) {
1716 if (is_string($element)) {
1717 if (!$this->elementExists($element)) {
1720 $element = $this->getElement($element);
1723 if (is_a($element, 'HTML_QuickForm_group')) {
1724 $elsInGroup = $element->getElements();
1726 foreach ($elsInGroup as $elInGroup){
1727 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1728 // not sure if this would work - groups nested in groups
1729 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1731 $elNames[] = $element->getElementName($elInGroup->getName());
1735 } else if (is_a($element, 'HTML_QuickForm_header')) {
1738 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1741 } else if (method_exists($element, 'getPrivateName')) {
1742 return array($element->getPrivateName());
1745 $elNames = array($element->getName());
1752 * Adds a dependency for $elementName which will be disabled if $condition is met.
1753 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1754 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1755 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1756 * of the $dependentOn element is $condition (such as equal) to $value.
1758 * @param string $elementName the name of the element which will be disabled
1759 * @param string $dependentOn the name of the element whose state will be checked for
1761 * @param string $condition the condition to check
1762 * @param mixed $value used in conjunction with condition.
1764 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1765 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1766 $this->_dependencies[$dependentOn] = array();
1768 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1769 $this->_dependencies[$dependentOn][$condition] = array();
1771 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1772 $this->_dependencies[$dependentOn][$condition][$value] = array();
1774 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1777 function registerNoSubmitButton($buttonname){
1778 $this->_noSubmitButtons[]=$buttonname;
1782 * @param string $buttonname
1785 function isNoSubmitButton($buttonname){
1786 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1790 * @param string $buttonname
1792 function _registerCancelButton($addfieldsname){
1793 $this->_cancelButtons[]=$addfieldsname;
1796 * Displays elements without HTML input tags.
1797 * This method is different to freeze() in that it makes sure no hidden
1798 * elements are included in the form.
1799 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1801 * This function also removes all previously defined rules.
1803 * @param mixed $elementList array or string of element(s) to be frozen
1806 function hardFreeze($elementList=null)
1808 if (!isset($elementList)) {
1809 $this->_freezeAll = true;
1810 $elementList = array();
1812 if (!is_array($elementList)) {
1813 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1815 $elementList = array_flip($elementList);
1818 foreach (array_keys($this->_elements) as $key) {
1819 $name = $this->_elements[$key]->getName();
1820 if ($this->_freezeAll || isset($elementList[$name])) {
1821 $this->_elements[$key]->freeze();
1822 $this->_elements[$key]->setPersistantFreeze(false);
1823 unset($elementList[$name]);
1826 $this->_rules[$name] = array();
1827 // if field is required, remove the rule
1828 $unset = array_search($name, $this->_required);
1829 if ($unset !== false) {
1830 unset($this->_required[$unset]);
1835 if (!empty($elementList)) {
1836 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);
1841 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1843 * This function also removes all previously defined rules of elements it freezes.
1845 * throws HTML_QuickForm_Error
1847 * @param array $elementList array or string of element(s) not to be frozen
1850 function hardFreezeAllVisibleExcept($elementList)
1852 $elementList = array_flip($elementList);
1853 foreach (array_keys($this->_elements) as $key) {
1854 $name = $this->_elements[$key]->getName();
1855 $type = $this->_elements[$key]->getType();
1857 if ($type == 'hidden'){
1858 // leave hidden types as they are
1859 } elseif (!isset($elementList[$name])) {
1860 $this->_elements[$key]->freeze();
1861 $this->_elements[$key]->setPersistantFreeze(false);
1864 $this->_rules[$name] = array();
1865 // if field is required, remove the rule
1866 $unset = array_search($name, $this->_required);
1867 if ($unset !== false) {
1868 unset($this->_required[$unset]);
1875 * Tells whether the form was already submitted
1877 * This is useful since the _submitFiles and _submitValues arrays
1878 * may be completely empty after the trackSubmit value is removed.
1883 function isSubmitted()
1885 return parent::isSubmitted() && (!$this->isFrozen());
1891 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1892 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1894 * Stylesheet is part of standard theme and should be automatically included.
1896 * @package moodlecore
1897 * @copyright Jamie Pratt <me@jamiep.org>
1898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1900 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1903 * Element template array
1907 var $_elementTemplates;
1909 * Template used when opening a hidden fieldset
1910 * (i.e. a fieldset that is opened when there is no header element)
1914 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1916 * Header Template string
1920 var $_headerTemplate =
1921 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1924 * Template used when opening a fieldset
1928 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1931 * Template used when closing a fieldset
1935 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1938 * Required Note template string
1942 var $_requiredNoteTemplate =
1943 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1945 var $_advancedElements = array();
1948 * Whether to display advanced elements (on page load)
1950 * @var integer 1 means show 0 means hide
1954 function MoodleQuickForm_Renderer(){
1955 // switch next two lines for ol li containers for form items.
1956 // $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>');
1957 $this->_elementTemplates = array(
1958 '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>',
1960 '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>',
1962 '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>',
1964 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
1968 parent::HTML_QuickForm_Renderer_Tableless();
1972 * @param array $elements
1974 function setAdvancedElements($elements){
1975 $this->_advancedElements = $elements;
1979 * What to do when starting the form
1981 * @param object $form MoodleQuickForm
1983 function startForm(&$form){
1984 $this->_reqHTML = $form->getReqHTML();
1985 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1986 $this->_advancedHTML = $form->getAdvancedHTML();
1987 $this->_showAdvanced = $form->getShowAdvanced();
1988 parent::startForm($form);
1989 if ($form->isFrozen()){
1990 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
1992 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
1993 $this->_hiddenHtml .= $form->_pageparams;
2000 * @param object $group Passed by reference
2001 * @param mixed $required
2002 * @param mixed $error
2004 function startGroup(&$group, $required, $error){
2005 if (method_exists($group, 'getElementTemplateType')){
2006 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2008 $html = $this->_elementTemplates['default'];
2011 if ($this->_showAdvanced){
2012 $advclass = ' advanced';
2014 $advclass = ' advanced hide';
2016 if (isset($this->_advancedElements[$group->getName()])){
2017 $html =str_replace(' {advanced}', $advclass, $html);
2018 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2020 $html =str_replace(' {advanced}', '', $html);
2021 $html =str_replace('{advancedimg}', '', $html);
2023 if (method_exists($group, 'getHelpButton')){
2024 $html =str_replace('{help}', $group->getHelpButton(), $html);
2026 $html =str_replace('{help}', '', $html);
2028 $html =str_replace('{name}', $group->getName(), $html);
2029 $html =str_replace('{type}', 'fgroup', $html);
2031 $this->_templates[$group->getName()]=$html;
2032 // Fix for bug in tableless quickforms that didn't allow you to stop a
2033 // fieldset before a group of elements.
2034 // if the element name indicates the end of a fieldset, close the fieldset
2035 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2036 && $this->_fieldsetsOpen > 0
2038 $this->_html .= $this->_closeFieldsetTemplate;
2039 $this->_fieldsetsOpen--;
2041 parent::startGroup($group, $required, $error);
2044 * @param object $element
2045 * @param mixed $required
2046 * @param mixed $error
2048 function renderElement(&$element, $required, $error){
2049 //manipulate id of all elements before rendering
2050 if (!is_null($element->getAttribute('id'))) {
2051 $id = $element->getAttribute('id');
2053 $id = $element->getName();
2055 //strip qf_ prefix and replace '[' with '_' and strip ']'
2056 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
2057 if (strpos($id, 'id_') !== 0){
2058 $element->updateAttributes(array('id'=>'id_'.$id));
2061 //adding stuff to place holders in template
2062 //check if this is a group element first
2063 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2064 // so it gets substitutions for *each* element
2065 $html = $this->_groupElementTemplate;
2067 elseif (method_exists($element, 'getElementTemplateType')){
2068 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2070 $html = $this->_elementTemplates['default'];
2072 if ($this->_showAdvanced){
2073 $advclass = ' advanced';
2075 $advclass = ' advanced hide';
2077 if (isset($this->_advancedElements[$element->getName()])){
2078 $html =str_replace(' {advanced}', $advclass, $html);
2080 $html =str_replace(' {advanced}', '', $html);
2082 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2083 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2085 $html =str_replace('{advancedimg}', '', $html);
2087 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2088 $html =str_replace('{name}', $element->getName(), $html);
2089 if (method_exists($element, 'getHelpButton')){
2090 $html = str_replace('{help}', $element->getHelpButton(), $html);
2092 $html = str_replace('{help}', '', $html);
2095 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2096 $this->_groupElementTemplate = $html;
2098 elseif (!isset($this->_templates[$element->getName()])) {
2099 $this->_templates[$element->getName()] = $html;
2102 parent::renderElement($element, $required, $error);
2106 * @param object $form Passed by reference
2108 function finishForm(&$form){
2109 if ($form->isFrozen()){
2110 $this->_hiddenHtml = '';
2112 parent::finishForm($form);
2113 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
2114 // add a lockoptions script
2115 $this->_html = $this->_html . "\n" . $script;
2119 * Called when visiting a header element
2121 * @param object $header An HTML_QuickForm_header element being visited
2125 function renderHeader(&$header) {
2127 static $advformcount;
2129 // This ensures that if 2(+) advanced buttons are used
2130 // that all show/hide buttons appear in the correct place
2131 // Because of now using $PAGE->requires->js_function_call
2132 if ($advformcount==null) {
2136 $name = $header->getName();
2138 $id = empty($name) ? '' : ' id="' . $name . '"';
2139 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2140 if (is_null($header->_text)) {
2142 } elseif (!empty($name) && isset($this->_templates[$name])) {
2143 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2145 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2148 if (isset($this->_advancedElements[$name])){
2149 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2151 $header_html =str_replace('{advancedimg}', '', $header_html);
2153 $elementName='mform_showadvanced';
2154 if ($this->_showAdvanced==0){
2155 $buttonlabel = get_string('showadvanced', 'form');
2157 $buttonlabel = get_string('hideadvanced', 'form');
2160 if (isset($this->_advancedElements[$name])){
2161 $PAGE->requires->yui2_lib('event');
2162 // this is tricky - the first submit button on form is "clicked" if user presses enter
2163 // we do not want to "submit" using advanced button if javascript active
2164 $button_nojs = '<input name="'.$elementName.'" id="'.$elementName.(string)$advformcount.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2166 $buttonlabel = addslashes_js($buttonlabel);
2167 $PAGE->requires->string_for_js('showadvanced', 'form');
2168 $PAGE->requires->string_for_js('hideadvanced', 'form');
2169 $PAGE->requires->js_function_call('showAdvancedInit', Array($elementName.(string)$advformcount, $elementName, $buttonlabel));
2172 $header_html = str_replace('{button}', $button_nojs, $header_html);
2174 $header_html = str_replace('{button}', '', $header_html);
2177 if ($this->_fieldsetsOpen > 0) {
2178 $this->_html .= $this->_closeFieldsetTemplate;
2179 $this->_fieldsetsOpen--;
2182 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2183 if ($this->_showAdvanced){
2184 $advclass = ' class="advanced"';
2186 $advclass = ' class="advanced hide"';
2188 if (isset($this->_advancedElements[$name])){
2189 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2191 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2193 $this->_html .= $openFieldsetTemplate . $header_html;
2194 $this->_fieldsetsOpen++;
2195 } // end func renderHeader
2197 function getStopFieldsetElements(){
2198 return $this->_stopFieldsetElements;
2203 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2204 * @name $_HTML_QuickForm_default_renderer
2206 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2208 /** Please keep this list in alphabetical order. */
2209 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2210 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2211 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2212 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2213 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2214 MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
2215 MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
2216 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2217 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2218 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2219 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2220 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2221 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2222 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2223 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2224 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2225 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2226 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2227 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2228 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2229 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2230 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2231 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2232 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2233 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2234 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2235 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2236 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2237 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2238 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2239 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2240 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2241 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2242 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2243 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2244 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2245 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2246 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');