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 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') ||
die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir
.'/filelib.php';
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
58 function pear_handle_error($error){
59 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60 echo '<br /> <strong>Backtrace </strong>:';
61 print_object($error->backtrace
);
64 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_ALL
){
65 PEAR
::setErrorHandling(PEAR_ERROR_CALLBACK
, 'pear_handle_error');
69 * Initalize javascript for date type form element
71 * @staticvar bool $done make sure it gets initalize once.
72 * @global moodle_page $PAGE
74 function form_init_date_js() {
78 $module = 'moodle-form-dateselector';
79 $function = 'M.form.dateselector.init_date_selectors';
80 $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
81 $PAGE->requires
->yui_module($module, $function, $config);
87 * Wrapper that separates quickforms syntax from moodle code
89 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
90 * use this class you should write a class definition which extends this class or a more specific
91 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
93 * You will write your own definition() method which performs the form set up.
96 * @copyright 2006 Jamie Pratt <me@jamiep.org>
97 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
98 * @todo MDL-19380 rethink the file scanning
100 abstract class moodleform
{
101 /** @var string name of the form */
102 protected $_formname; // form name
104 /** @var MoodleQuickForm quickform object definition */
107 /** @var array globals workaround */
108 protected $_customdata;
110 /** @var object definition_after_data executed flag */
111 protected $_definition_finalized = false;
114 * The constructor function calls the abstract function definition() and it will then
115 * process and clean and attempt to validate incoming data.
117 * It will call your custom validate method to validate data and will also check any rules
118 * you have specified in definition using addRule
120 * The name of the form (id attribute of the form) is automatically generated depending on
121 * the name you gave the class extending moodleform. You should call your class something
124 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
125 * current url. If a moodle_url object then outputs params as hidden variables.
126 * @param mixed $customdata if your form defintion method needs access to data such as $course
127 * $cm, etc. to construct the form definition then pass it in this array. You can
128 * use globals for somethings.
129 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
130 * be merged and used as incoming data to the form.
131 * @param string $target target frame for form submission. You will rarely use this. Don't use
132 * it if you don't need to as the target attribute is deprecated in xhtml strict.
133 * @param mixed $attributes you can pass a string of html attributes here or an array.
134 * @param bool $editable
136 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
138 if (empty($CFG->xmlstrictheaders
)) {
139 // no standard mform in moodle should allow autocomplete with the exception of user signup
140 // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0
141 if (empty($attributes)) {
142 $attributes = array('autocomplete'=>'off');
143 } else if (is_array($attributes)) {
144 $attributes['autocomplete'] = 'off';
146 if (strpos($attributes, 'autocomplete') === false) {
147 $attributes .= ' autocomplete="off" ';
153 $action = strip_querystring(qualified_me());
155 // Assign custom data first, so that get_form_identifier can use it.
156 $this->_customdata
= $customdata;
157 $this->_formname
= $this->get_form_identifier();
159 $this->_form
= new MoodleQuickForm($this->_formname
, $method, $action, $target, $attributes);
161 $this->_form
->hardFreeze();
166 $this->_form
->addElement('hidden', 'sesskey', null); // automatic sesskey protection
167 $this->_form
->setType('sesskey', PARAM_RAW
);
168 $this->_form
->setDefault('sesskey', sesskey());
169 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
170 $this->_form
->setType('_qf__'.$this->_formname
, PARAM_RAW
);
171 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
172 $this->_form
->_setDefaultRuleMessages();
174 // we have to know all input types before processing submission ;-)
175 $this->_process_submission($method);
179 * It should returns unique identifier for the form.
180 * Currently it will return class name, but in case two same forms have to be
181 * rendered on same page then override function to get unique form identifier.
182 * e.g This is used on multiple self enrollments page.
184 * @return string form identifier.
186 protected function get_form_identifier() {
187 return get_class($this);
191 * To autofocus on first form element or first element with error.
193 * @param string $name if this is set then the focus is forced to a field with this name
194 * @return string javascript to select form element with first error or
195 * first element if no errors. Use this as a parameter
196 * when calling print_header
198 function focus($name=NULL) {
199 $form =& $this->_form
;
200 $elkeys = array_keys($form->_elementIndex
);
202 if (isset($form->_errors
) && 0 != count($form->_errors
)){
203 $errorkeys = array_keys($form->_errors
);
204 $elkeys = array_intersect($elkeys, $errorkeys);
208 if ($error or empty($name)) {
210 while (empty($names) and !empty($elkeys)) {
211 $el = array_shift($elkeys);
212 $names = $form->_getElNamesRecursive($el);
214 if (!empty($names)) {
215 $name = array_shift($names);
221 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
228 * Internal method. Alters submitted data to be suitable for quickforms processing.
229 * Must be called when the form is fully set up.
231 * @param string $method name of the method which alters submitted data
233 function _process_submission($method) {
234 $submission = array();
235 if ($method == 'post') {
236 if (!empty($_POST)) {
237 $submission = $_POST;
240 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
243 // following trick is needed to enable proper sesskey checks when using GET forms
244 // the _qf__.$this->_formname serves as a marker that form was actually submitted
245 if (array_key_exists('_qf__'.$this->_formname
, $submission) and $submission['_qf__'.$this->_formname
] == 1) {
246 if (!confirm_sesskey()) {
247 print_error('invalidsesskey');
251 $submission = array();
255 $this->_form
->updateSubmission($submission, $files);
259 * Internal method. Validates all old-style deprecated uploaded files.
260 * The new way is to upload files via repository api.
262 * @param array $files list of files to be validated
263 * @return bool|array Success or an array of errors
265 function _validate_files(&$files) {
266 global $CFG, $COURSE;
270 if (empty($_FILES)) {
271 // we do not need to do any checks because no files were submitted
272 // note: server side rules do not work for files - use custom verification in validate() instead
277 $filenames = array();
279 // now check that we really want each file
280 foreach ($_FILES as $elname=>$file) {
281 $required = $this->_form
->isElementRequired($elname);
283 if ($file['error'] == 4 and $file['size'] == 0) {
285 $errors[$elname] = get_string('required');
287 unset($_FILES[$elname]);
291 if (!empty($file['error'])) {
292 $errors[$elname] = file_get_upload_error($file['error']);
293 unset($_FILES[$elname]);
297 if (!is_uploaded_file($file['tmp_name'])) {
298 // TODO: improve error message
299 $errors[$elname] = get_string('error');
300 unset($_FILES[$elname]);
304 if (!$this->_form
->elementExists($elname) or !$this->_form
->getElementType($elname)=='file') {
305 // hmm, this file was not requested
306 unset($_FILES[$elname]);
311 // TODO: rethink the file scanning MDL-19380
312 if ($CFG->runclamonupload) {
313 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
314 $errors[$elname] = $_FILES[$elname]['uploadlog'];
315 unset($_FILES[$elname]);
320 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE
);
321 if ($filename === '') {
322 // TODO: improve error message - wrong chars
323 $errors[$elname] = get_string('error');
324 unset($_FILES[$elname]);
327 if (in_array($filename, $filenames)) {
328 // TODO: improve error message - duplicate name
329 $errors[$elname] = get_string('error');
330 unset($_FILES[$elname]);
333 $filenames[] = $filename;
334 $_FILES[$elname]['name'] = $filename;
336 $files[$elname] = $_FILES[$elname]['tmp_name'];
339 // return errors if found
340 if (count($errors) == 0){
350 * Internal method. Validates filepicker and filemanager files if they are
351 * set as required fields. Also, sets the error message if encountered one.
353 * @return bool|array with errors
355 protected function validate_draft_files() {
357 $mform =& $this->_form
;
360 //Go through all the required elements and make sure you hit filepicker or
361 //filemanager element.
362 foreach ($mform->_rules
as $elementname => $rules) {
363 $elementtype = $mform->getElementType($elementname);
364 //If element is of type filepicker then do validation
365 if (($elementtype == 'filepicker') ||
($elementtype == 'filemanager')){
366 //Check if rule defined is required rule
367 foreach ($rules as $rule) {
368 if ($rule['type'] == 'required') {
369 $draftid = (int)$mform->getSubmitValue($elementname);
370 $fs = get_file_storage();
371 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
372 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
373 $errors[$elementname] = $rule['message'];
379 if (empty($errors)) {
387 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
388 * form definition (new entry form); this function is used to load in data where values
389 * already exist and data is being edited (edit entry form).
391 * note: $slashed param removed
393 * @param stdClass|array $default_values object or array of default values
395 function set_data($default_values) {
396 if (is_object($default_values)) {
397 $default_values = (array)$default_values;
399 $this->_form
->setDefaults($default_values);
403 * Sets file upload manager
405 * @deprecated since Moodle 2.0 Please don't used this API
406 * @todo MDL-31300 this api will be removed.
407 * @see MoodleQuickForm_filepicker
408 * @see MoodleQuickForm_filemanager
409 * @param bool $um upload manager
411 function set_upload_manager($um=false) {
412 debugging('Old file uploads can not be used any more, please use new filepicker element');
416 * Check that form was submitted. Does not check validity of submitted data.
418 * @return bool true if form properly submitted
420 function is_submitted() {
421 return $this->_form
->isSubmitted();
425 * Checks if button pressed is not for submitting the form
427 * @staticvar bool $nosubmit keeps track of no submit button
430 function no_submit_button_pressed(){
431 static $nosubmit = null; // one check is enough
432 if (!is_null($nosubmit)){
435 $mform =& $this->_form
;
437 if (!$this->is_submitted()){
440 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
441 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
451 * Check that form data is valid.
452 * You should almost always use this, rather than {@link validate_defined_fields}
454 * @return bool true if form data valid
456 function is_validated() {
457 //finalize the form definition before any processing
458 if (!$this->_definition_finalized
) {
459 $this->_definition_finalized
= true;
460 $this->definition_after_data();
463 return $this->validate_defined_fields();
469 * You almost always want to call {@link is_validated} instead of this
470 * because it calls {@link definition_after_data} first, before validating the form,
471 * which is what you want in 99% of cases.
473 * This is provided as a separate function for those special cases where
474 * you want the form validated before definition_after_data is called
475 * for example, to selectively add new elements depending on a no_submit_button press,
476 * but only when the form is valid when the no_submit_button is pressed,
478 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
479 * is NOT to validate the form when a no submit button has been pressed.
480 * pass true here to override this behaviour
482 * @return bool true if form data valid
484 function validate_defined_fields($validateonnosubmit=false) {
485 static $validated = null; // one validation is enough
486 $mform =& $this->_form
;
487 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
489 } elseif ($validated === null) {
490 $internal_val = $mform->validate();
493 $file_val = $this->_validate_files($files);
494 //check draft files for validation and flag them if required files
495 //are not in draft area.
496 $draftfilevalue = $this->validate_draft_files();
498 if ($file_val !== true && $draftfilevalue !== true) {
499 $file_val = array_merge($file_val, $draftfilevalue);
500 } else if ($draftfilevalue !== true) {
501 $file_val = $draftfilevalue;
502 } //default is file_val, so no need to assign.
504 if ($file_val !== true) {
505 if (!empty($file_val)) {
506 foreach ($file_val as $element=>$msg) {
507 $mform->setElementError($element, $msg);
513 $data = $mform->exportValues();
514 $moodle_val = $this->validation($data, $files);
515 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
516 // non-empty array means errors
517 foreach ($moodle_val as $element=>$msg) {
518 $mform->setElementError($element, $msg);
523 // anything else means validation ok
527 $validated = ($internal_val and $moodle_val and $file_val);
533 * Return true if a cancel button has been pressed resulting in the form being submitted.
535 * @return bool true if a cancel button has been pressed
537 function is_cancelled(){
538 $mform =& $this->_form
;
539 if ($mform->isSubmitted()){
540 foreach ($mform->_cancelButtons
as $cancelbutton){
541 if (optional_param($cancelbutton, 0, PARAM_RAW
)){
550 * Return submitted data if properly submitted or returns NULL if validation fails or
551 * if there is no submitted data.
553 * note: $slashed param removed
555 * @return object submitted data; NULL if not valid or not submitted or cancelled
557 function get_data() {
558 $mform =& $this->_form
;
560 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
561 $data = $mform->exportValues();
562 unset($data['sesskey']); // we do not need to return sesskey
563 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
567 return (object)$data;
575 * Return submitted data without validation or NULL if there is no submitted data.
576 * note: $slashed param removed
578 * @return object submitted data; NULL if not submitted
580 function get_submitted_data() {
581 $mform =& $this->_form
;
583 if ($this->is_submitted()) {
584 $data = $mform->exportValues();
585 unset($data['sesskey']); // we do not need to return sesskey
586 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
590 return (object)$data;
598 * Save verified uploaded files into directory. Upload process can be customised from definition()
600 * @deprecated since Moodle 2.0
601 * @todo MDL-31294 remove this api
602 * @see moodleform::save_stored_file()
603 * @see moodleform::save_file()
604 * @param string $destination path where file should be stored
605 * @return bool Always false
607 function save_files($destination) {
608 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
613 * Returns name of uploaded file.
615 * @param string $elname first element if null
616 * @return string|bool false in case of failure, string if ok
618 function get_new_filename($elname=null) {
621 if (!$this->is_submitted() or !$this->is_validated()) {
625 if (is_null($elname)) {
626 if (empty($_FILES)) {
630 $elname = key($_FILES);
633 if (empty($elname)) {
637 $element = $this->_form
->getElement($elname);
639 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
640 $values = $this->_form
->exportValues($elname);
641 if (empty($values[$elname])) {
644 $draftid = $values[$elname];
645 $fs = get_file_storage();
646 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
647 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
650 $file = reset($files);
651 return $file->get_filename();
654 if (!isset($_FILES[$elname])) {
658 return $_FILES[$elname]['name'];
662 * Save file to standard filesystem
664 * @param string $elname name of element
665 * @param string $pathname full path name of file
666 * @param bool $override override file if exists
667 * @return bool success
669 function save_file($elname, $pathname, $override=false) {
672 if (!$this->is_submitted() or !$this->is_validated()) {
675 if (file_exists($pathname)) {
677 if (!@unlink
($pathname)) {
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)) {
698 $file = reset($files);
700 return $file->copy_content_to($pathname);
702 } else if (isset($_FILES[$elname])) {
703 return copy($_FILES[$elname]['tmp_name'], $pathname);
710 * Returns a temporary file, do not forget to delete after not needed any more.
712 * @param string $elname name of the elmenet
713 * @return string|bool either string or false
715 function save_temp_file($elname) {
716 if (!$this->get_new_filename($elname)) {
719 if (!$dir = make_temp_directory('forms')) {
722 if (!$tempfile = tempnam($dir, 'tempup_')) {
725 if (!$this->save_file($elname, $tempfile, true)) {
726 // something went wrong
735 * Get draft files of a form element
736 * This is a protected method which will be used only inside moodleforms
738 * @param string $elname name of element
739 * @return array|bool|null
741 protected function get_draft_files($elname) {
744 if (!$this->is_submitted()) {
748 $element = $this->_form
->getElement($elname);
750 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
751 $values = $this->_form
->exportValues($elname);
752 if (empty($values[$elname])) {
755 $draftid = $values[$elname];
756 $fs = get_file_storage();
757 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
758 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
767 * Save file to local filesystem pool
769 * @param string $elname name of element
770 * @param int $newcontextid id of context
771 * @param string $newcomponent name of the component
772 * @param string $newfilearea name of file area
773 * @param int $newitemid item id
774 * @param string $newfilepath path of file where it get stored
775 * @param string $newfilename use specified filename, if not specified name of uploaded file used
776 * @param bool $overwrite overwrite file if exists
777 * @param int $newuserid new userid if required
778 * @return mixed stored_file object or false if error; may throw exception if duplicate found
780 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
781 $newfilename=null, $overwrite=false, $newuserid=null) {
784 if (!$this->is_submitted() or !$this->is_validated()) {
788 if (empty($newuserid)) {
789 $newuserid = $USER->id
;
792 $element = $this->_form
->getElement($elname);
793 $fs = get_file_storage();
795 if ($element instanceof MoodleQuickForm_filepicker
) {
796 $values = $this->_form
->exportValues($elname);
797 if (empty($values[$elname])) {
800 $draftid = $values[$elname];
801 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
802 if (!$files = $fs->get_area_files($context->id
, 'user' ,'draft', $draftid, 'id DESC', false)) {
805 $file = reset($files);
806 if (is_null($newfilename)) {
807 $newfilename = $file->get_filename();
811 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
812 if (!$oldfile->delete()) {
818 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
819 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
820 return $fs->create_file_from_storedfile($file_record, $file);
822 } else if (isset($_FILES[$elname])) {
823 $filename = is_null($newfilename) ?
$_FILES[$elname]['name'] : $newfilename;
826 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
827 if (!$oldfile->delete()) {
833 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
834 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
835 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
842 * Get content of uploaded file.
844 * @param string $elname name of file upload element
845 * @return string|bool false in case of failure, string if ok
847 function get_file_content($elname) {
850 if (!$this->is_submitted() or !$this->is_validated()) {
854 $element = $this->_form
->getElement($elname);
856 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
857 $values = $this->_form
->exportValues($elname);
858 if (empty($values[$elname])) {
861 $draftid = $values[$elname];
862 $fs = get_file_storage();
863 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
864 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
867 $file = reset($files);
869 return $file->get_content();
871 } else if (isset($_FILES[$elname])) {
872 return file_get_contents($_FILES[$elname]['tmp_name']);
882 //finalize the form definition if not yet done
883 if (!$this->_definition_finalized
) {
884 $this->_definition_finalized
= true;
885 $this->definition_after_data();
887 $this->_form
->display();
891 * Form definition. Abstract method - always override!
893 protected abstract function definition();
896 * Dummy stub method - override if you need to setup the form depending on current
897 * values. This method is called after definition(), data submission and set_data().
898 * All form setup that is dependent on form values should go in here.
900 function definition_after_data(){
904 * Dummy stub method - override if you needed to perform some extra validation.
905 * If there are errors return array of errors ("fieldname"=>"error message"),
906 * otherwise true if ok.
908 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
910 * @param array $data array of ("fieldname"=>value) of submitted data
911 * @param array $files array of uploaded files "element_name"=>tmp_file_path
912 * @return array of "element_name"=>"error_description" if there are errors,
913 * or an empty array if everything is OK (true allowed for backwards compatibility too).
915 function validation($data, $files) {
920 * Helper used by {@link repeat_elements()}.
922 * @param int $i the index of this element.
923 * @param HTML_QuickForm_element $elementclone
924 * @param array $namecloned array of names
926 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
927 $name = $elementclone->getName();
928 $namecloned[] = $name;
931 $elementclone->setName($name."[$i]");
934 if (is_a($elementclone, 'HTML_QuickForm_header')) {
935 $value = $elementclone->_text
;
936 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
939 $value=$elementclone->getLabel();
940 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
945 * Method to add a repeating group of elements to a form.
947 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
948 * @param int $repeats no of times to repeat elements initially
949 * @param array $options Array of options to apply to elements. Array keys are element names.
950 * This is an array of arrays. The second sets of keys are the option types for the elements :
951 * 'default' - default value is value
952 * 'type' - PARAM_* constant is value
953 * 'helpbutton' - helpbutton params array is value
954 * 'disabledif' - last three moodleform::disabledIf()
955 * params are value as an array
956 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
957 * @param string $addfieldsname name for button to add more fields
958 * @param int $addfieldsno how many fields to add at a time
959 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
960 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
961 * @return int no of repeats of element in this page
963 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
964 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
965 if ($addstring===null){
966 $addstring = get_string('addfields', 'form', $addfieldsno);
968 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
970 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT
);
971 $addfields = optional_param($addfieldsname, '', PARAM_TEXT
);
972 if (!empty($addfields)){
973 $repeats +
= $addfieldsno;
975 $mform =& $this->_form
;
976 $mform->registerNoSubmitButton($addfieldsname);
977 $mform->addElement('hidden', $repeathiddenname, $repeats);
978 $mform->setType($repeathiddenname, PARAM_INT
);
979 //value not to be overridden by submitted value
980 $mform->setConstants(array($repeathiddenname=>$repeats));
981 $namecloned = array();
982 for ($i = 0; $i < $repeats; $i++
) {
983 foreach ($elementobjs as $elementobj){
984 $elementclone = fullclone($elementobj);
985 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
987 if ($elementclone instanceof HTML_QuickForm_group
&& !$elementclone->_appendName
) {
988 foreach ($elementclone->getElements() as $el) {
989 $this->repeat_elements_fix_clone($i, $el, $namecloned);
991 $elementclone->setLabel(str_replace('{no}', $i +
1, $elementclone->getLabel()));
994 $mform->addElement($elementclone);
997 for ($i=0; $i<$repeats; $i++
) {
998 foreach ($options as $elementname => $elementoptions){
999 $pos=strpos($elementname, '[');
1001 $realelementname = substr($elementname, 0, $pos+
1)."[$i]";
1002 $realelementname .= substr($elementname, $pos+
1);
1004 $realelementname = $elementname."[$i]";
1006 foreach ($elementoptions as $option => $params){
1010 $mform->setDefault($realelementname, $params);
1013 $params = array_merge(array($realelementname), $params);
1014 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1017 foreach ($namecloned as $num => $name){
1018 if ($params[0] == $name){
1019 $params[0] = $params[0]."[$i]";
1023 $params = array_merge(array($realelementname), $params);
1024 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1027 if (is_string($params)){
1028 $params = array(null, $params, null, 'client');
1030 $params = array_merge(array($realelementname), $params);
1031 call_user_func_array(array(&$mform, 'addRule'), $params);
1034 //Type should be set only once
1035 if (!isset($mform->_types
[$elementname])) {
1036 $mform->setType($elementname, $params);
1043 $mform->addElement('submit', $addfieldsname, $addstring);
1045 if (!$addbuttoninside) {
1046 $mform->closeHeaderBefore($addfieldsname);
1053 * Adds a link/button that controls the checked state of a group of checkboxes.
1055 * @param int $groupid The id of the group of advcheckboxes this element controls
1056 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1057 * @param array $attributes associative array of HTML attributes
1058 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1060 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1063 // Set the default text if none was specified
1065 $text = get_string('selectallornone', 'form');
1068 $mform = $this->_form
;
1069 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT
);
1071 if ($select_value == 0 ||
is_null($select_value)) {
1072 $new_select_value = 1;
1074 $new_select_value = 0;
1077 $mform->addElement('hidden', "checkbox_controller$groupid");
1078 $mform->setType("checkbox_controller$groupid", PARAM_INT
);
1079 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
1081 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
1082 $mform->registerNoSubmitButton($checkbox_controller_name);
1084 // Prepare Javascript for submit element
1085 $js = "\n//<![CDATA[\n";
1086 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
1088 function html_quickform_toggle_checkboxes(group) {
1089 var checkboxes = document.getElementsByClassName('checkboxgroup' + group);
1090 var newvalue = false;
1091 var global = eval('html_quickform_checkboxgroup' + group + ';');
1093 eval('html_quickform_checkboxgroup' + group + ' = 0;');
1096 eval('html_quickform_checkboxgroup' + group + ' = 1;');
1097 newvalue = 'checked';
1100 for (i = 0; i < checkboxes.length; i++) {
1101 checkboxes[i].checked = newvalue;
1105 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
1107 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
1111 require_once("$CFG->libdir/form/submitlink.php");
1112 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
1113 $submitlink->_js
= $js;
1114 $submitlink->_onclick
= "html_quickform_toggle_checkboxes($groupid); return false;";
1115 $mform->addElement($submitlink);
1116 $mform->setDefault($checkbox_controller_name, $text);
1120 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1121 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1122 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1123 * get data with get_data().
1125 * @param bool $cancel whether to show cancel button, default true
1126 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1128 function add_action_buttons($cancel = true, $submitlabel=null){
1129 if (is_null($submitlabel)){
1130 $submitlabel = get_string('savechanges');
1132 $mform =& $this->_form
;
1134 //when two elements we need a group
1135 $buttonarray=array();
1136 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1137 $buttonarray[] = &$mform->createElement('cancel');
1138 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1139 $mform->closeHeaderBefore('buttonar');
1142 $mform->addElement('submit', 'submitbutton', $submitlabel);
1143 $mform->closeHeaderBefore('submitbutton');
1148 * Adds an initialisation call for a standard JavaScript enhancement.
1150 * This function is designed to add an initialisation call for a JavaScript
1151 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1155 * - smartselect: Turns a nbsp indented select box into a custom drop down
1156 * control that supports multilevel and category selection.
1157 * $enhancement = 'smartselect';
1158 * $options = array('selectablecategories' => true|false)
1161 * @param string|element $element form element for which Javascript needs to be initalized
1162 * @param string $enhancement which init function should be called
1163 * @param array $options options passed to javascript
1164 * @param array $strings strings for javascript
1166 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1168 if (is_string($element)) {
1169 $element = $this->_form
->getElement($element);
1171 if (is_object($element)) {
1172 $element->_generateId();
1173 $elementid = $element->getAttribute('id');
1174 $PAGE->requires
->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1175 if (is_array($strings)) {
1176 foreach ($strings as $string) {
1177 if (is_array($string)) {
1178 call_user_method_array('string_for_js', $PAGE->requires
, $string);
1180 $PAGE->requires
->string_for_js($string, 'moodle');
1188 * Returns a JS module definition for the mforms JS
1192 public static function get_js_module() {
1196 'fullpath' => '/lib/form/form.js',
1197 'requires' => array('base', 'node'),
1199 array('showadvanced', 'form'),
1200 array('hideadvanced', 'form')
1207 * MoodleQuickForm implementation
1209 * You never extend this class directly. The class methods of this class are available from
1210 * the private $this->_form property on moodleform and its children. You generally only
1211 * call methods on this class from within abstract methods that you override on moodleform such
1212 * as definition and definition_after_data
1214 * @package core_form
1216 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1217 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1219 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
1220 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1221 var $_types = array();
1223 /** @var array dependent state for the element/'s */
1224 var $_dependencies = array();
1226 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1227 var $_noSubmitButtons=array();
1229 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1230 var $_cancelButtons=array();
1232 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1233 var $_advancedElements = array();
1235 /** @var bool Whether to display advanced elements (on page load) */
1236 var $_showAdvanced = null;
1239 * The form name is derived from the class name of the wrapper minus the trailing form
1240 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1243 var $_formName = '';
1246 * String with the html for hidden params passed in as part of a moodle_url
1247 * object for the action. Output in the form.
1250 var $_pageparams = '';
1253 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1255 * @staticvar int $formcounter counts number of forms
1256 * @param string $formName Form's name.
1257 * @param string $method Form's method defaults to 'POST'
1258 * @param string|moodle_url $action Form's action
1259 * @param string $target (optional)Form's target defaults to none
1260 * @param mixed $attributes (optional)Extra attributes for <form> tag
1262 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1263 global $CFG, $OUTPUT;
1265 static $formcounter = 1;
1267 HTML_Common
::HTML_Common($attributes);
1268 $target = empty($target) ?
array() : array('target' => $target);
1269 $this->_formName
= $formName;
1270 if (is_a($action, 'moodle_url')){
1271 $this->_pageparams
= html_writer
::input_hidden_params($action);
1272 $action = $action->out_omit_querystring();
1274 $this->_pageparams
= '';
1276 //no 'name' atttribute for form in xhtml strict :
1277 $attributes = array('action'=>$action, 'method'=>$method,
1278 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) +
$target;
1280 $this->updateAttributes($attributes);
1282 //this is custom stuff for Moodle :
1283 $oldclass= $this->getAttribute('class');
1284 if (!empty($oldclass)){
1285 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1287 $this->updateAttributes(array('class'=>'mform'));
1289 $this->_reqHTML
= '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1290 $this->_advancedHTML
= '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1291 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1295 * Use this method to indicate an element in a form is an advanced field. If items in a form
1296 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1297 * form so the user can decide whether to display advanced form controls.
1299 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1301 * @param string $elementName group or element name (not the element name of something inside a group).
1302 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1304 function setAdvanced($elementName, $advanced=true){
1306 $this->_advancedElements
[$elementName]='';
1307 } elseif (isset($this->_advancedElements
[$elementName])) {
1308 unset($this->_advancedElements
[$elementName]);
1310 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1311 $this->setShowAdvanced();
1312 $this->registerNoSubmitButton('mform_showadvanced');
1314 $this->addElement('hidden', 'mform_showadvanced_last');
1315 $this->setType('mform_showadvanced_last', PARAM_INT
);
1319 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1320 * display advanced elements in the form until 'Show Advanced' is pressed.
1322 * You can get the last state of the form and possibly save it for this user by using
1323 * value 'mform_showadvanced_last' in submitted data.
1325 * @param bool $showadvancedNow if true will show adavance elements.
1327 function setShowAdvanced($showadvancedNow = null){
1328 if ($showadvancedNow === null){
1329 if ($this->_showAdvanced
!== null){
1331 } else { //if setShowAdvanced is called without any preference
1332 //make the default to not show advanced elements.
1333 $showadvancedNow = get_user_preferences(
1334 textlib
::strtolower($this->_formName
.'_showadvanced', 0));
1337 //value of hidden element
1338 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT
);
1340 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW
);
1341 //toggle if button pressed or else stay the same
1342 if ($hiddenLast == -1) {
1343 $next = $showadvancedNow;
1344 } elseif ($buttonPressed) { //toggle on button press
1345 $next = !$hiddenLast;
1347 $next = $hiddenLast;
1349 $this->_showAdvanced
= $next;
1350 if ($showadvancedNow != $next){
1351 set_user_preference($this->_formName
.'_showadvanced', $next);
1353 $this->setConstants(array('mform_showadvanced_last'=>$next));
1357 * Gets show advance value, if advance elements are visible it will return true else false
1361 function getShowAdvanced(){
1362 return $this->_showAdvanced
;
1367 * Accepts a renderer
1369 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1371 function accept(&$renderer) {
1372 if (method_exists($renderer, 'setAdvancedElements')){
1373 //check for visible fieldsets where all elements are advanced
1374 //and mark these headers as advanced as well.
1375 //And mark all elements in a advanced header as advanced
1376 $stopFields = $renderer->getStopFieldSetElements();
1378 $lastHeaderAdvanced = false;
1379 $anyAdvanced = false;
1380 foreach (array_keys($this->_elements
) as $elementIndex){
1381 $element =& $this->_elements
[$elementIndex];
1383 // if closing header and any contained element was advanced then mark it as advanced
1384 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
1385 if ($anyAdvanced && !is_null($lastHeader)){
1386 $this->setAdvanced($lastHeader->getName());
1388 $lastHeaderAdvanced = false;
1391 } elseif ($lastHeaderAdvanced) {
1392 $this->setAdvanced($element->getName());
1395 if ($element->getType()=='header'){
1396 $lastHeader =& $element;
1397 $anyAdvanced = false;
1398 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
1399 } elseif (isset($this->_advancedElements
[$element->getName()])){
1400 $anyAdvanced = true;
1403 // the last header may not be closed yet...
1404 if ($anyAdvanced && !is_null($lastHeader)){
1405 $this->setAdvanced($lastHeader->getName());
1407 $renderer->setAdvancedElements($this->_advancedElements
);
1410 parent
::accept($renderer);
1414 * Adds one or more element names that indicate the end of a fieldset
1416 * @param string $elementName name of the element
1418 function closeHeaderBefore($elementName){
1419 $renderer =& $this->defaultRenderer();
1420 $renderer->addStopFieldsetElements($elementName);
1424 * Should be used for all elements of a form except for select, radio and checkboxes which
1425 * clean their own data.
1427 * @param string $elementname
1428 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1429 * {@link lib/moodlelib.php} for defined parameter types
1431 function setType($elementname, $paramtype) {
1432 $this->_types
[$elementname] = $paramtype;
1436 * This can be used to set several types at once.
1438 * @param array $paramtypes types of parameters.
1439 * @see MoodleQuickForm::setType
1441 function setTypes($paramtypes) {
1442 $this->_types
= $paramtypes +
$this->_types
;
1446 * Updates submitted values
1448 * @param array $submission submitted values
1449 * @param array $files list of files
1451 function updateSubmission($submission, $files) {
1452 $this->_flagSubmitted
= false;
1454 if (empty($submission)) {
1455 $this->_submitValues
= array();
1457 foreach ($submission as $key=>$s) {
1458 if (array_key_exists($key, $this->_types
)) {
1459 $type = $this->_types
[$key];
1464 $submission[$key] = clean_param_array($s, $type, true);
1466 $submission[$key] = clean_param($s, $type);
1469 $this->_submitValues
= $submission;
1470 $this->_flagSubmitted
= true;
1473 if (empty($files)) {
1474 $this->_submitFiles
= array();
1476 $this->_submitFiles
= $files;
1477 $this->_flagSubmitted
= true;
1480 // need to tell all elements that they need to update their value attribute.
1481 foreach (array_keys($this->_elements
) as $key) {
1482 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
1487 * Returns HTML for required elements
1491 function getReqHTML(){
1492 return $this->_reqHTML
;
1496 * Returns HTML for advanced elements
1500 function getAdvancedHTML(){
1501 return $this->_advancedHTML
;
1505 * Initializes a default form value. Used to specify the default for a new entry where
1506 * no data is loaded in using moodleform::set_data()
1508 * note: $slashed param removed
1510 * @param string $elementName element name
1511 * @param mixed $defaultValue values for that element name
1513 function setDefault($elementName, $defaultValue){
1514 $this->setDefaults(array($elementName=>$defaultValue));
1518 * Add an array of buttons to the form
1520 * @param array $buttons An associative array representing help button to attach to
1521 * to the form. keys of array correspond to names of elements in form.
1522 * @param bool $suppresscheck if true then string check will be suppressed
1523 * @param string $function callback function to dispaly help button.
1524 * @deprecated since Moodle 2.0 use addHelpButton() call on each element manually
1525 * @todo MDL-31047 this api will be removed.
1526 * @see MoodleQuickForm::addHelpButton()
1528 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1530 debugging('function moodle_form::setHelpButtons() is deprecated');
1531 //foreach ($buttons as $elementname => $button){
1532 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1537 * Add a help button to element
1539 * @param string $elementname name of the element to add the item to
1540 * @param array $buttonargs arguments to pass to function $function
1541 * @param bool $suppresscheck whether to throw an error if the element
1543 * @param string $function - function to generate html from the arguments in $button
1544 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1545 * @todo MDL-31047 this api will be removed.
1546 * @see MoodleQuickForm::addHelpButton()
1548 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1551 debugging('function moodle_form::setHelpButton() is deprecated');
1552 if ($function !== 'helpbutton') {
1553 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1556 $buttonargs = (array)$buttonargs;
1558 if (array_key_exists($elementname, $this->_elementIndex
)) {
1559 //_elements has a numeric index, this code accesses the elements by name
1560 $element = $this->_elements
[$this->_elementIndex
[$elementname]];
1562 $page = isset($buttonargs[0]) ?
$buttonargs[0] : null;
1563 $text = isset($buttonargs[1]) ?
$buttonargs[1] : null;
1564 $module = isset($buttonargs[2]) ?
$buttonargs[2] : 'moodle';
1565 $linktext = isset($buttonargs[3]) ?
$buttonargs[3] : false;
1567 $element->_helpbutton
= $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1569 } else if (!$suppresscheck) {
1570 print_error('nonexistentformelements', 'form', '', $elementname);
1575 * Add a help button to element, only one button per element is allowed.
1577 * This is new, simplified and preferable method of setting a help icon on form elements.
1578 * It uses the new $OUTPUT->help_icon().
1580 * Typically, you will provide the same identifier and the component as you have used for the
1581 * label of the element. The string identifier with the _help suffix added is then used
1582 * as the help string.
1584 * There has to be two strings defined:
1585 * 1/ get_string($identifier, $component) - the title of the help page
1586 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1589 * @param string $elementname name of the element to add the item to
1590 * @param string $identifier help string identifier without _help suffix
1591 * @param string $component component name to look the help string in
1592 * @param string $linktext optional text to display next to the icon
1593 * @param bool $suppresscheck set to true if the element may not exist
1595 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1597 if (array_key_exists($elementname, $this->_elementIndex
)) {
1598 $element = $this->_elements
[$this->_elementIndex
[$elementname]];
1599 $element->_helpbutton
= $OUTPUT->help_icon($identifier, $component, $linktext);
1600 } else if (!$suppresscheck) {
1601 debugging(get_string('nonexistentformelements', 'form', $elementname));
1606 * Set constant value not overridden by _POST or _GET
1607 * note: this does not work for complex names with [] :-(
1609 * @param string $elname name of element
1610 * @param mixed $value
1612 function setConstant($elname, $value) {
1613 $this->_constantValues
= HTML_QuickForm
::arrayMerge($this->_constantValues
, array($elname=>$value));
1614 $element =& $this->getElement($elname);
1615 $element->onQuickFormEvent('updateValue', null, $this);
1619 * export submitted values
1621 * @param string $elementList list of elements in form
1624 function exportValues($elementList = null){
1625 $unfiltered = array();
1626 if (null === $elementList) {
1627 // iterate over all elements, calling their exportValue() methods
1628 $emptyarray = array();
1629 foreach (array_keys($this->_elements
) as $key) {
1630 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
){
1631 $value = $this->_elements
[$key]->exportValue($emptyarray, true);
1633 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
1636 if (is_array($value)) {
1637 // This shit throws a bogus warning in PHP 4.3.x
1638 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
1642 if (!is_array($elementList)) {
1643 $elementList = array_map('trim', explode(',', $elementList));
1645 foreach ($elementList as $elementName) {
1646 $value = $this->exportValue($elementName);
1647 if (PEAR
::isError($value)) {
1650 //oh, stock QuickFOrm was returning array of arrays!
1651 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
1655 if (is_array($this->_constantValues
)) {
1656 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $this->_constantValues
);
1663 * Adds a validation rule for the given field
1665 * If the element is in fact a group, it will be considered as a whole.
1666 * To validate grouped elements as separated entities,
1667 * use addGroupRule instead of addRule.
1669 * @param string $element Form element name
1670 * @param string $message Message to display for invalid data
1671 * @param string $type Rule type, use getRegisteredRules() to get types
1672 * @param string $format (optional)Required for extra rule data
1673 * @param string $validation (optional)Where to perform validation: "server", "client"
1674 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1675 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1677 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1679 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
1680 if ($validation == 'client') {
1681 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1687 * Adds a validation rule for the given group of elements
1689 * Only groups with a name can be assigned a validation rule
1690 * Use addGroupRule when you need to validate elements inside the group.
1691 * Use addRule if you need to validate the group as a whole. In this case,
1692 * the same rule will be applied to all elements in the group.
1693 * Use addRule if you need to validate the group against a function.
1695 * @param string $group Form group name
1696 * @param array|string $arg1 Array for multiple elements or error message string for one element
1697 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1698 * @param string $format (optional)Required for extra rule data
1699 * @param int $howmany (optional)How many valid elements should be in the group
1700 * @param string $validation (optional)Where to perform validation: "server", "client"
1701 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1703 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1705 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1706 if (is_array($arg1)) {
1707 foreach ($arg1 as $rules) {
1708 foreach ($rules as $rule) {
1709 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
1711 if ('client' == $validation) {
1712 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1716 } elseif (is_string($arg1)) {
1718 if ($validation == 'client') {
1719 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1725 * Returns the client side validation script
1727 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1728 * and slightly modified to run rules per-element
1729 * Needed to override this because of an error with client side validation of grouped elements.
1731 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1733 function getValidationScript()
1735 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1739 include_once('HTML/QuickForm/RuleRegistry.php');
1740 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1751 foreach ($this->_rules
as $elementName => $rules) {
1752 foreach ($rules as $rule) {
1753 if ('client' == $rule['validation']) {
1754 unset($element); //TODO: find out how to properly initialize it
1756 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1757 $rule['message'] = strtr($rule['message'], $js_escape);
1759 if (isset($rule['group'])) {
1760 $group =& $this->getElement($rule['group']);
1761 // No JavaScript validation for frozen elements
1762 if ($group->isFrozen()) {
1765 $elements =& $group->getElements();
1766 foreach (array_keys($elements) as $key) {
1767 if ($elementName == $group->getElementName($key)) {
1768 $element =& $elements[$key];
1772 } elseif ($dependent) {
1774 $element[] =& $this->getElement($elementName);
1775 foreach ($rule['dependent'] as $elName) {
1776 $element[] =& $this->getElement($elName);
1779 $element =& $this->getElement($elementName);
1781 // No JavaScript validation for frozen elements
1782 if (is_object($element) && $element->isFrozen()) {
1784 } elseif (is_array($element)) {
1785 foreach (array_keys($element) as $key) {
1786 if ($element[$key]->isFrozen()) {
1791 //for editor element, [text] is appended to the name.
1792 if ($element->getType() == 'editor') {
1793 $elementName .= '[text]';
1794 //Add format to rule as moodleform check which format is supported by browser
1795 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1796 if (is_null($rule['format'])) {
1797 $rule['format'] = $element->getFormat();
1800 // Fix for bug displaying errors for elements in a group
1801 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1802 $test[$elementName][1]=$element;
1808 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1809 // the form, and then that form field gets corrupted by the code that follows.
1813 <script type="text/javascript">
1816 var skipClientValidation = false;
1818 function qf_errorHandler(element, _qfMsg) {
1819 div = element.parentNode;
1821 if ((div == undefined) || (element.name == undefined)) {
1822 //no checking can be done for undefined elements so let server handle it.
1826 if (_qfMsg != \'\') {
1827 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1829 errorSpan = document.createElement("span");
1830 errorSpan.id = \'id_error_\'+element.name;
1831 errorSpan.className = "error";
1832 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1835 while (errorSpan.firstChild) {
1836 errorSpan.removeChild(errorSpan.firstChild);
1839 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1840 errorSpan.appendChild(document.createElement("br"));
1842 if (div.className.substr(div.className.length - 6, 6) != " error"
1843 && div.className != "error") {
1844 div.className += " error";
1849 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1851 errorSpan.parentNode.removeChild(errorSpan);
1854 if (div.className.substr(div.className.length - 6, 6) == " error") {
1855 div.className = div.className.substr(0, div.className.length - 6);
1856 } else if (div.className == "error") {
1864 foreach ($test as $elementName => $jsandelement) {
1865 // Fix for bug displaying errors for elements in a group
1867 list($jsArr,$element)=$jsandelement;
1869 $escapedElementName = preg_replace_callback(
1871 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1874 function validate_' . $this->_formName
. '_' . $escapedElementName . '(element) {
1875 if (undefined == element) {
1876 //required element was not found, then let form be submitted without client side validation
1880 var errFlag = new Array();
1883 var frm = element.parentNode;
1884 if ((undefined != element.name) && (frm != undefined)) {
1885 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1886 frm = frm.parentNode;
1888 ' . join("\n", $jsArr) . '
1889 return qf_errorHandler(element, _qfMsg);
1891 //element name should be defined else error msg will not be displayed.
1897 ret = validate_' . $this->_formName
. '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1898 if (!ret && !first_focus) {
1900 frm.elements[\''.$elementName.'\'].focus();
1904 // Fix for bug displaying errors for elements in a group
1906 //$element =& $this->getElement($elementName);
1908 $valFunc = 'validate_' . $this->_formName
. '_' . $escapedElementName . '(this)';
1909 $onBlur = $element->getAttribute('onBlur');
1910 $onChange = $element->getAttribute('onChange');
1911 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1912 'onChange' => $onChange . $valFunc));
1914 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1916 function validate_' . $this->_formName
. '(frm) {
1917 if (skipClientValidation) {
1922 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1923 var first_focus = false;
1924 ' . $validateJS . ';
1930 } // end func getValidationScript
1933 * Sets default error message
1935 function _setDefaultRuleMessages(){
1936 foreach ($this->_rules
as $field => $rulesarr){
1937 foreach ($rulesarr as $key => $rule){
1938 if ($rule['message']===null){
1940 $a->format
=$rule['format'];
1941 $str=get_string('err_'.$rule['type'], 'form', $a);
1942 if (strpos($str, '[[')!==0){
1943 $this->_rules
[$field][$key]['message']=$str;
1951 * Get list of attributes which have dependencies
1955 function getLockOptionObject(){
1957 foreach ($this->_dependencies
as $dependentOn => $conditions){
1958 $result[$dependentOn] = array();
1959 foreach ($conditions as $condition=>$values) {
1960 $result[$dependentOn][$condition] = array();
1961 foreach ($values as $value=>$dependents) {
1962 $result[$dependentOn][$condition][$value] = array();
1964 foreach ($dependents as $dependent) {
1965 $elements = $this->_getElNamesRecursive($dependent);
1966 if (empty($elements)) {
1967 // probably element inside of some group
1968 $elements = array($dependent);
1970 foreach($elements as $element) {
1971 if ($element == $dependentOn) {
1974 $result[$dependentOn][$condition][$value][] = $element;
1980 return array($this->getAttribute('id'), $result);
1984 * Get names of element or elements in a group.
1986 * @param HTML_QuickForm_group|element $element element group or element object
1989 function _getElNamesRecursive($element) {
1990 if (is_string($element)) {
1991 if (!$this->elementExists($element)) {
1994 $element = $this->getElement($element);
1997 if (is_a($element, 'HTML_QuickForm_group')) {
1998 $elsInGroup = $element->getElements();
2000 foreach ($elsInGroup as $elInGroup){
2001 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2002 // not sure if this would work - groups nested in groups
2003 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2005 $elNames[] = $element->getElementName($elInGroup->getName());
2009 } else if (is_a($element, 'HTML_QuickForm_header')) {
2012 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2015 } else if (method_exists($element, 'getPrivateName') &&
2016 !($element instanceof HTML_QuickForm_advcheckbox
)) {
2017 // The advcheckbox element implements a method called getPrivateName,
2018 // but in a way that is not compatible with the generic API, so we
2019 // have to explicitly exclude it.
2020 return array($element->getPrivateName());
2023 $elNames = array($element->getName());
2030 * Adds a dependency for $elementName which will be disabled if $condition is met.
2031 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2032 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2033 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2034 * of the $dependentOn element is $condition (such as equal) to $value.
2036 * @param string $elementName the name of the element which will be disabled
2037 * @param string $dependentOn the name of the element whose state will be checked for condition
2038 * @param string $condition the condition to check
2039 * @param mixed $value used in conjunction with condition.
2041 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2042 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
2043 $this->_dependencies
[$dependentOn] = array();
2045 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
2046 $this->_dependencies
[$dependentOn][$condition] = array();
2048 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
2049 $this->_dependencies
[$dependentOn][$condition][$value] = array();
2051 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
2055 * Registers button as no submit button
2057 * @param string $buttonname name of the button
2059 function registerNoSubmitButton($buttonname){
2060 $this->_noSubmitButtons
[]=$buttonname;
2064 * Checks if button is a no submit button, i.e it doesn't submit form
2066 * @param string $buttonname name of the button to check
2069 function isNoSubmitButton($buttonname){
2070 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
2074 * Registers a button as cancel button
2076 * @param string $addfieldsname name of the button
2078 function _registerCancelButton($addfieldsname){
2079 $this->_cancelButtons
[]=$addfieldsname;
2083 * Displays elements without HTML input tags.
2084 * This method is different to freeze() in that it makes sure no hidden
2085 * elements are included in the form.
2086 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2088 * This function also removes all previously defined rules.
2090 * @param string|array $elementList array or string of element(s) to be frozen
2091 * @return object|bool if element list is not empty then return error object, else true
2093 function hardFreeze($elementList=null)
2095 if (!isset($elementList)) {
2096 $this->_freezeAll
= true;
2097 $elementList = array();
2099 if (!is_array($elementList)) {
2100 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2102 $elementList = array_flip($elementList);
2105 foreach (array_keys($this->_elements
) as $key) {
2106 $name = $this->_elements
[$key]->getName();
2107 if ($this->_freezeAll ||
isset($elementList[$name])) {
2108 $this->_elements
[$key]->freeze();
2109 $this->_elements
[$key]->setPersistantFreeze(false);
2110 unset($elementList[$name]);
2113 $this->_rules
[$name] = array();
2114 // if field is required, remove the rule
2115 $unset = array_search($name, $this->_required
);
2116 if ($unset !== false) {
2117 unset($this->_required
[$unset]);
2122 if (!empty($elementList)) {
2123 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);
2129 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2131 * This function also removes all previously defined rules of elements it freezes.
2133 * @throws HTML_QuickForm_Error
2134 * @param array $elementList array or string of element(s) not to be frozen
2135 * @return bool returns true
2137 function hardFreezeAllVisibleExcept($elementList)
2139 $elementList = array_flip($elementList);
2140 foreach (array_keys($this->_elements
) as $key) {
2141 $name = $this->_elements
[$key]->getName();
2142 $type = $this->_elements
[$key]->getType();
2144 if ($type == 'hidden'){
2145 // leave hidden types as they are
2146 } elseif (!isset($elementList[$name])) {
2147 $this->_elements
[$key]->freeze();
2148 $this->_elements
[$key]->setPersistantFreeze(false);
2151 $this->_rules
[$name] = array();
2152 // if field is required, remove the rule
2153 $unset = array_search($name, $this->_required
);
2154 if ($unset !== false) {
2155 unset($this->_required
[$unset]);
2163 * Tells whether the form was already submitted
2165 * This is useful since the _submitFiles and _submitValues arrays
2166 * may be completely empty after the trackSubmit value is removed.
2170 function isSubmitted()
2172 return parent
::isSubmitted() && (!$this->isFrozen());
2177 * MoodleQuickForm renderer
2179 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2180 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2182 * Stylesheet is part of standard theme and should be automatically included.
2184 * @package core_form
2185 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2186 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2188 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
2190 /** @var array Element template array */
2191 var $_elementTemplates;
2194 * Template used when opening a hidden fieldset
2195 * (i.e. a fieldset that is opened when there is no header element)
2198 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2200 /** @var string Header Template string */
2201 var $_headerTemplate =
2202 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2204 /** @var string Template used when opening a fieldset */
2205 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2207 /** @var string Template used when closing a fieldset */
2208 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2210 /** @var string Required Note template string */
2211 var $_requiredNoteTemplate =
2212 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2214 /** @var array list of elements which are marked as advance and will be grouped together */
2215 var $_advancedElements = array();
2217 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2223 function MoodleQuickForm_Renderer(){
2224 // switch next two lines for ol li containers for form items.
2225 // $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>');
2226 $this->_elementTemplates
= array(
2227 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><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>',
2229 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><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>',
2231 '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>',
2233 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2237 parent
::HTML_QuickForm_Renderer_Tableless();
2241 * Set element's as adavance element
2243 * @param array $elements form elements which needs to be grouped as advance elements.
2245 function setAdvancedElements($elements){
2246 $this->_advancedElements
= $elements;
2250 * What to do when starting the form
2252 * @param MoodleQuickForm $form reference of the form
2254 function startForm(&$form){
2256 $this->_reqHTML
= $form->getReqHTML();
2257 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
2258 $this->_advancedHTML
= $form->getAdvancedHTML();
2259 $this->_showAdvanced
= $form->getShowAdvanced();
2260 parent
::startForm($form);
2261 if ($form->isFrozen()){
2262 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
2264 $this->_formTemplate
= "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2265 $this->_hiddenHtml
.= $form->_pageparams
;
2268 $PAGE->requires
->yui_module('moodle-core-formchangechecker',
2269 'M.core_formchangechecker.init',
2271 'formid' => $form->getAttribute('id')
2274 $PAGE->requires
->string_for_js('changesmadereallygoaway', 'moodle');
2278 * Create advance group of elements
2280 * @param object $group Passed by reference
2281 * @param bool $required if input is required field
2282 * @param string $error error message to display
2284 function startGroup(&$group, $required, $error){
2285 // Make sure the element has an id.
2286 $group->_generateId();
2288 if (method_exists($group, 'getElementTemplateType')){
2289 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
2291 $html = $this->_elementTemplates
['default'];
2294 if ($this->_showAdvanced
){
2295 $advclass = ' advanced';
2297 $advclass = ' advanced hide';
2299 if (isset($this->_advancedElements
[$group->getName()])){
2300 $html =str_replace(' {advanced}', $advclass, $html);
2301 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
2303 $html =str_replace(' {advanced}', '', $html);
2304 $html =str_replace('{advancedimg}', '', $html);
2306 if (method_exists($group, 'getHelpButton')){
2307 $html =str_replace('{help}', $group->getHelpButton(), $html);
2309 $html =str_replace('{help}', '', $html);
2311 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2312 $html =str_replace('{name}', $group->getName(), $html);
2313 $html =str_replace('{type}', 'fgroup', $html);
2315 $this->_templates
[$group->getName()]=$html;
2316 // Fix for bug in tableless quickforms that didn't allow you to stop a
2317 // fieldset before a group of elements.
2318 // if the element name indicates the end of a fieldset, close the fieldset
2319 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
2320 && $this->_fieldsetsOpen
> 0
2322 $this->_html
.= $this->_closeFieldsetTemplate
;
2323 $this->_fieldsetsOpen
--;
2325 parent
::startGroup($group, $required, $error);
2330 * @param HTML_QuickForm_element $element element
2331 * @param bool $required if input is required field
2332 * @param string $error error message to display
2334 function renderElement(&$element, $required, $error){
2335 // Make sure the element has an id.
2336 $element->_generateId();
2338 //adding stuff to place holders in template
2339 //check if this is a group element first
2340 if (($this->_inGroup
) and !empty($this->_groupElementTemplate
)) {
2341 // so it gets substitutions for *each* element
2342 $html = $this->_groupElementTemplate
;
2344 elseif (method_exists($element, 'getElementTemplateType')){
2345 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
2347 $html = $this->_elementTemplates
['default'];
2349 if ($this->_showAdvanced
){
2350 $advclass = ' advanced';
2352 $advclass = ' advanced hide';
2354 if (isset($this->_advancedElements
[$element->getName()])){
2355 $html =str_replace(' {advanced}', $advclass, $html);
2357 $html =str_replace(' {advanced}', '', $html);
2359 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
2360 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
2362 $html =str_replace('{advancedimg}', '', $html);
2364 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2365 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2366 $html =str_replace('{name}', $element->getName(), $html);
2367 if (method_exists($element, 'getHelpButton')){
2368 $html = str_replace('{help}', $element->getHelpButton(), $html);
2370 $html = str_replace('{help}', '', $html);
2373 if (($this->_inGroup
) and !empty($this->_groupElementTemplate
)) {
2374 $this->_groupElementTemplate
= $html;
2376 elseif (!isset($this->_templates
[$element->getName()])) {
2377 $this->_templates
[$element->getName()] = $html;
2380 parent
::renderElement($element, $required, $error);
2384 * Called when visiting a form, after processing all form elements
2385 * Adds required note, form attributes, validation javascript and form content.
2387 * @global moodle_page $PAGE
2388 * @param moodleform $form Passed by reference
2390 function finishForm(&$form){
2392 if ($form->isFrozen()){
2393 $this->_hiddenHtml
= '';
2395 parent
::finishForm($form);
2396 if (!$form->isFrozen()) {
2397 $args = $form->getLockOptionObject();
2398 if (count($args[1]) > 0) {
2399 $PAGE->requires
->js_init_call('M.form.initFormDependencies', $args, true, moodleform
::get_js_module());
2404 * Called when visiting a header element
2406 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2407 * @global moodle_page $PAGE
2409 function renderHeader(&$header) {
2412 $name = $header->getName();
2414 $id = empty($name) ?
'' : ' id="' . $name . '"';
2415 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2416 if (is_null($header->_text
)) {
2418 } elseif (!empty($name) && isset($this->_templates
[$name])) {
2419 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
2421 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
2424 if (isset($this->_advancedElements
[$name])){
2425 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
2426 $elementName='mform_showadvanced';
2427 if ($this->_showAdvanced
==0){
2428 $buttonlabel = get_string('showadvanced', 'form');
2430 $buttonlabel = get_string('hideadvanced', 'form');
2432 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2433 $PAGE->requires
->js_init_call('M.form.initShowAdvanced', array(), false, moodleform
::get_js_module());
2434 $header_html = str_replace('{button}', $button, $header_html);
2436 $header_html =str_replace('{advancedimg}', '', $header_html);
2437 $header_html = str_replace('{button}', '', $header_html);
2440 if ($this->_fieldsetsOpen
> 0) {
2441 $this->_html
.= $this->_closeFieldsetTemplate
;
2442 $this->_fieldsetsOpen
--;
2445 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
2446 if ($this->_showAdvanced
){
2447 $advclass = ' class="advanced"';
2449 $advclass = ' class="advanced hide"';
2451 if (isset($this->_advancedElements
[$name])){
2452 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2454 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2456 $this->_html
.= $openFieldsetTemplate . $header_html;
2457 $this->_fieldsetsOpen++
;
2461 * Return Array of element names that indicate the end of a fieldset
2465 function getStopFieldsetElements(){
2466 return $this->_stopFieldsetElements
;
2471 * Required elements validation
2473 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2475 * @package core_form
2477 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2480 class MoodleQuickForm_Rule_Required
extends HTML_QuickForm_Rule
{
2482 * Checks if an element is not empty.
2483 * This is a server-side validation, it works for both text fields and editor fields
2485 * @param string $value Value to check
2486 * @param int|string|array $options Not used yet
2487 * @return bool true if value is not empty
2489 function validate($value, $options = null) {
2491 if (is_array($value) && array_key_exists('text', $value)) {
2492 $value = $value['text'];
2494 if (is_array($value)) {
2495 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2496 $value = implode('', $value);
2498 $stripvalues = array(
2499 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2500 '#(\xc2|\xa0|\s| )#', //any whitespaces actually
2502 if (!empty($CFG->strictformsrequired
)) {
2503 $value = preg_replace($stripvalues, '', (string)$value);
2505 if ((string)$value == '') {
2512 * This function returns Javascript code used to build client-side validation.
2513 * It checks if an element is not empty.
2515 * @param int $format format of data which needs to be validated.
2518 function getValidationScript($format = null) {
2520 if (!empty($CFG->strictformsrequired
)) {
2521 if (!empty($format) && $format == FORMAT_HTML
) {
2522 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)| |\s+/ig, '') == ''");
2524 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2527 return array('', "{jsVar} == ''");
2533 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2534 * @name $_HTML_QuickForm_default_renderer
2536 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2538 /** Please keep this list in alphabetical order. */
2539 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2540 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2541 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2542 MoodleQuickForm
::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2543 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2544 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2545 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2546 MoodleQuickForm
::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2547 MoodleQuickForm
::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2548 MoodleQuickForm
::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2549 MoodleQuickForm
::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2550 MoodleQuickForm
::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2551 MoodleQuickForm
::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2552 MoodleQuickForm
::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2553 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2554 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2555 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2556 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2557 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2558 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2559 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2560 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2561 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2562 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2563 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2564 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2565 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2566 MoodleQuickForm
::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2567 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2568 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2569 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2570 MoodleQuickForm
::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2571 MoodleQuickForm
::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2572 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2573 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2574 MoodleQuickForm
::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2575 MoodleQuickForm
::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2577 MoodleQuickForm
::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");