weekly release 1.9.13+
[moodle.git] / lib / formslib.php
blobd0743c3f56eb0ad655728bbbd0d27853447247d3
1 <?php // $Id$
2 /**
3 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
5 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
6 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
7 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
8 * and validation.
10 * See examples of use of this library in course/edit.php and course/edit_form.php
12 * A few notes :
13 * form defintion is used for both printing of form and processing and should be the same
14 * for both or you may lose some submitted data which won't be let through.
15 * you should be using setType for every form element except select, radio or checkbox
16 * elements, these elements clean themselves.
19 * @author Jamie Pratt
20 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
23 if (!defined('MOODLE_INTERNAL')) {
24 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
28 //setup.php icludes our hacked pear libs first
29 require_once 'HTML/QuickForm.php';
30 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
31 require_once 'HTML/QuickForm/Renderer/Tableless.php';
33 require_once $CFG->libdir.'/uploadlib.php';
35 /**
36 * Callback called when PEAR throws an error
38 * @param PEAR_Error $error
40 function pear_handle_error($error){
41 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
42 echo '<br /> <strong>Backtrace </strong>:';
43 print_object($error->backtrace);
46 if ($CFG->debug >= DEBUG_ALL){
47 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
51 /**
52 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
53 * use this class you should write a class definition which extends this class or a more specific
54 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
56 * You will write your own definition() method which performs the form set up.
58 class moodleform {
59 var $_formname; // form name
60 /**
61 * quickform object definition
63 * @var MoodleQuickForm
65 var $_form;
66 /**
67 * globals workaround
69 * @var array
71 var $_customdata;
72 /**
73 * file upload manager
75 * @var upload_manager
77 var $_upload_manager; //
78 /**
79 * definition_after_data executed flag
80 * @var definition_finalized
82 var $_definition_finalized = false;
84 /**
85 * The constructor function calls the abstract function definition() and it will then
86 * process and clean and attempt to validate incoming data.
88 * It will call your custom validate method to validate data and will also check any rules
89 * you have specified in definition using addRule
91 * The name of the form (id attribute of the form) is automatically generated depending on
92 * the name you gave the class extending moodleform. You should call your class something
93 * like
95 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
96 * current url. If a moodle_url object then outputs params as hidden variables.
97 * @param array $customdata if your form defintion method needs access to data such as $course
98 * $cm, etc. to construct the form definition then pass it in this array. You can
99 * use globals for somethings.
100 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
101 * be merged and used as incoming data to the form.
102 * @param string $target target frame for form submission. You will rarely use this. Don't use
103 * it if you don't need to as the target attribute is deprecated in xhtml
104 * strict.
105 * @param mixed $attributes you can pass a string of html attributes here or an array.
106 * @return moodleform
108 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
109 if (empty($action)){
110 $action = strip_querystring(qualified_me());
113 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
114 $this->_customdata = $customdata;
115 $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
116 if (!$editable){
117 $this->_form->hardFreeze();
119 $this->set_upload_manager(new upload_manager());
121 $this->definition();
123 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
124 $this->_form->setType('sesskey', PARAM_RAW);
125 $this->_form->setDefault('sesskey', sesskey());
126 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
127 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
128 $this->_form->setDefault('_qf__'.$this->_formname, 1);
129 $this->_form->_setDefaultRuleMessages();
131 // we have to know all input types before processing submission ;-)
132 $this->_process_submission($method);
136 * To autofocus on first form element or first element with error.
138 * @param string $name if this is set then the focus is forced to a field with this name
140 * @return string javascript to select form element with first error or
141 * first element if no errors. Use this as a parameter
142 * when calling print_header
144 function focus($name=NULL) {
145 $form =& $this->_form;
146 $elkeys = array_keys($form->_elementIndex);
147 $error = false;
148 if (isset($form->_errors) && 0 != count($form->_errors)){
149 $errorkeys = array_keys($form->_errors);
150 $elkeys = array_intersect($elkeys, $errorkeys);
151 $error = true;
154 if ($error or empty($name)) {
155 $names = array();
156 while (empty($names) and !empty($elkeys)) {
157 $el = array_shift($elkeys);
158 $names = $form->_getElNamesRecursive($el);
160 if (!empty($names)) {
161 $name = array_shift($names);
165 $focus = '';
166 if (!empty($name)) {
167 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
170 return $focus;
174 * Internal method. Alters submitted data to be suitable for quickforms processing.
175 * Must be called when the form is fully set up.
177 function _process_submission($method) {
178 $submission = array();
179 if ($method == 'post') {
180 if (!empty($_POST)) {
181 $submission = $_POST;
183 } else {
184 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
187 // following trick is needed to enable proper sesskey checks when using GET forms
188 // the _qf__.$this->_formname serves as a marker that form was actually submitted
189 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
190 if (!confirm_sesskey()) {
191 print_error('invalidsesskey');
193 $files = $_FILES;
194 } else {
195 $submission = array();
196 $files = array();
199 $this->_form->updateSubmission($submission, $files);
203 * Internal method. Validates all uploaded files.
205 function _validate_files(&$files) {
206 $files = array();
208 if (empty($_FILES)) {
209 // we do not need to do any checks because no files were submitted
210 // note: server side rules do not work for files - use custom verification in validate() instead
211 return true;
213 $errors = array();
214 $mform =& $this->_form;
216 // check the files
217 $status = $this->_upload_manager->preprocess_files();
219 // now check that we really want each file
220 foreach ($_FILES as $elname=>$file) {
221 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
222 $required = $mform->isElementRequired($elname);
223 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
224 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
225 // file not uploaded and not required - ignore it
226 continue;
228 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
230 } else if (!empty($this->_upload_manager->files[$elname]['clear'])) {
231 $files[$elname] = $this->_upload_manager->files[$elname]['tmp_name'];
233 } else {
234 error('Incorrect upload attempt!');
238 // return errors if found
239 if ($status and 0 == count($errors)){
240 return true;
242 } else {
243 $files = array();
244 return $errors;
249 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
250 * form definition (new entry form); this function is used to load in data where values
251 * already exist and data is being edited (edit entry form).
253 * @param mixed $default_values object or array of default values
254 * @param bool $slased true if magic quotes applied to data values
256 function set_data($default_values, $slashed=false) {
257 if (is_object($default_values)) {
258 $default_values = (array)$default_values;
260 $filter = $slashed ? 'stripslashes' : NULL;
261 $this->_form->setDefaults($default_values, $filter);
265 * Set custom upload manager.
266 * Must be used BEFORE creating of file element!
268 * @param object $um - custom upload manager
270 function set_upload_manager($um=false) {
271 if ($um === false) {
272 $um = new upload_manager();
274 $this->_upload_manager = $um;
276 $this->_form->setMaxFileSize($um->config->maxbytes);
280 * Check that form was submitted. Does not check validity of submitted data.
282 * @return bool true if form properly submitted
284 function is_submitted() {
285 return $this->_form->isSubmitted();
288 function no_submit_button_pressed(){
289 static $nosubmit = null; // one check is enough
290 if (!is_null($nosubmit)){
291 return $nosubmit;
293 $mform =& $this->_form;
294 $nosubmit = false;
295 if (!$this->is_submitted()){
296 return false;
298 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
299 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
300 $nosubmit = true;
301 break;
304 return $nosubmit;
309 * Check that form data is valid.
310 * You should almost always use this, rather than {@see validate_defined_fields}
312 * @return bool true if form data valid
314 function is_validated() {
315 //finalize the form definition before any processing
316 if (!$this->_definition_finalized) {
317 $this->_definition_finalized = true;
318 $this->definition_after_data();
320 return $this->validate_defined_fields();
324 * Validate the form.
326 * You almost always want to call {@see is_validated} instead of this
327 * because it calls {@see definition_after_data} first, before validating the form,
328 * which is what you want in 99% of cases.
330 * This is provided as a separate function for those special cases where
331 * you want the form validated before definition_after_data is called
332 * for example, to selectively add new elements depending on a no_submit_button press,
333 * but only when the form is valid when the no_submit_button is pressed,
335 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
336 * is NOT to validate the form when a no submit button has been pressed.
337 * pass true here to override this behaviour
339 * @return bool true if form data valid
341 function validate_defined_fields($validateonnosubmit=false) {
342 static $validated = null; // one validation is enough
343 $mform =& $this->_form;
345 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
346 return false;
347 } elseif ($validated === null) {
348 $internal_val = $mform->validate();
350 $files = array();
351 $file_val = $this->_validate_files($files);
352 if ($file_val !== true) {
353 if (!empty($file_val)) {
354 foreach ($file_val as $element=>$msg) {
355 $mform->setElementError($element, $msg);
358 $file_val = false;
361 $data = $mform->exportValues(null, true);
362 $moodle_val = $this->validation($data, $files);
363 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
364 // non-empty array means errors
365 foreach ($moodle_val as $element=>$msg) {
366 $mform->setElementError($element, $msg);
368 $moodle_val = false;
370 } else {
371 // anything else means validation ok
372 $moodle_val = true;
375 $validated = ($internal_val and $moodle_val and $file_val);
377 return $validated;
381 * Return true if a cancel button has been pressed resulting in the form being submitted.
383 * @return boolean true if a cancel button has been pressed
385 function is_cancelled(){
386 $mform =& $this->_form;
387 if ($mform->isSubmitted()){
388 foreach ($mform->_cancelButtons as $cancelbutton){
389 if (optional_param($cancelbutton, 0, PARAM_RAW)){
390 return true;
394 return false;
398 * Return submitted data if properly submitted or returns NULL if validation fails or
399 * if there is no submitted data.
401 * @param bool $slashed true means return data with addslashes applied
402 * @return object submitted data; NULL if not valid or not submitted
404 function get_data($slashed=true) {
405 $mform =& $this->_form;
407 if ($this->is_submitted() and $this->is_validated()) {
408 $data = $mform->exportValues(null, $slashed);
409 unset($data['sesskey']); // we do not need to return sesskey
410 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
411 if (empty($data)) {
412 return NULL;
413 } else {
414 return (object)$data;
416 } else {
417 return NULL;
422 * Return submitted data without validation or NULL if there is no submitted data.
424 * @param bool $slashed true means return data with addslashes applied
425 * @return object submitted data; NULL if not submitted
427 function get_submitted_data($slashed=true) {
428 $mform =& $this->_form;
430 if ($this->is_submitted()) {
431 $data = $mform->exportValues(null, $slashed);
432 unset($data['sesskey']); // we do not need to return sesskey
433 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
434 if (empty($data)) {
435 return NULL;
436 } else {
437 return (object)$data;
439 } else {
440 return NULL;
445 * Save verified uploaded files into directory. Upload process can be customised from definition()
446 * method by creating instance of upload manager and storing it in $this->_upload_form
448 * @param string $destination where to store uploaded files
449 * @return bool success
451 function save_files($destination) {
452 if ($this->is_submitted() and $this->is_validated()) {
453 return $this->_upload_manager->save_files($destination);
455 return false;
459 * If we're only handling one file (if inputname was given in the constructor)
460 * this will return the (possibly changed) filename of the file.
461 * @return mixed false in case of failure, string if ok
463 function get_new_filename() {
464 return $this->_upload_manager->get_new_filename();
468 * Get content of uploaded file.
469 * @param $element name of file upload element
470 * @return mixed false in case of failure, string if ok
472 function get_file_content($elname) {
473 if (!$this->is_submitted() or !$this->is_validated()) {
474 return false;
477 if (!$this->_form->elementExists($elname)) {
478 return false;
481 if (empty($this->_upload_manager->files[$elname]['clear'])) {
482 return false;
485 if (empty($this->_upload_manager->files[$elname]['tmp_name'])) {
486 return false;
489 $data = "";
490 $file = @fopen($this->_upload_manager->files[$elname]['tmp_name'], "rb");
491 if ($file) {
492 while (!feof($file)) {
493 $data .= fread($file, 1024); // TODO: do we really have to do this?
495 fclose($file);
496 return $data;
497 } else {
498 return false;
503 * Print html form.
505 function display() {
506 //finalize the form definition if not yet done
507 if (!$this->_definition_finalized) {
508 $this->_definition_finalized = true;
509 $this->definition_after_data();
511 $this->_form->display();
515 * Abstract method - always override!
517 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
519 function definition() {
520 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
524 * Dummy stub method - override if you need to setup the form depending on current
525 * values. This method is called after definition(), data submission and set_data().
526 * All form setup that is dependent on form values should go in here.
528 function definition_after_data(){
532 * Dummy stub method - override if you needed to perform some extra validation.
533 * If there are errors return array of errors ("fieldname"=>"error message"),
534 * otherwise true if ok.
536 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
538 * @param array $data array of ("fieldname"=>value) of submitted data
539 * @param array $files array of uploaded files "element_name"=>tmp_file_path
540 * @return array of "element_name"=>"error_description" if there are errors,
541 * or an empty array if everything is OK (true allowed for backwards compatibility too).
543 function validation($data, $files) {
544 return array();
548 * Method to add a repeating group of elements to a form.
550 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
551 * @param integer $repeats no of times to repeat elements initially
552 * @param array $options Array of options to apply to elements. Array keys are element names.
553 * This is an array of arrays. The second sets of keys are the option types
554 * for the elements :
555 * 'default' - default value is value
556 * 'type' - PARAM_* constant is value
557 * 'helpbutton' - helpbutton params array is value
558 * 'disabledif' - last three moodleform::disabledIf()
559 * params are value as an array
560 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
561 * @param string $addfieldsname name for button to add more fields
562 * @param int $addfieldsno how many fields to add at a time
563 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
564 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
565 * @return int no of repeats of element in this page
567 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
568 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
569 if ($addstring===null){
570 $addstring = get_string('addfields', 'form', $addfieldsno);
571 } else {
572 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
574 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
575 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
576 if (!empty($addfields)){
577 $repeats += $addfieldsno;
579 $mform =& $this->_form;
580 $mform->registerNoSubmitButton($addfieldsname);
581 $mform->addElement('hidden', $repeathiddenname, $repeats);
582 $mform->setType($repeathiddenname, PARAM_INT);
583 //value not to be overridden by submitted value
584 $mform->setConstants(array($repeathiddenname=>$repeats));
585 $namecloned = array();
586 for ($i = 0; $i < $repeats; $i++) {
587 foreach ($elementobjs as $elementobj){
588 $elementclone = fullclone($elementobj);
589 $name = $elementclone->getName();
590 $namecloned[] = $name;
591 if (!empty($name)) {
592 $elementclone->setName($name."[$i]");
594 if (is_a($elementclone, 'HTML_QuickForm_header')) {
595 $value = $elementclone->_text;
596 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
598 } else {
599 $value=$elementclone->getLabel();
600 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
604 $mform->addElement($elementclone);
607 for ($i=0; $i<$repeats; $i++) {
608 foreach ($options as $elementname => $elementoptions){
609 $pos=strpos($elementname, '[');
610 if ($pos!==FALSE){
611 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
612 $realelementname .= substr($elementname, $pos+1);
613 }else {
614 $realelementname = $elementname."[$i]";
616 foreach ($elementoptions as $option => $params){
618 switch ($option){
619 case 'default' :
620 $mform->setDefault($realelementname, $params);
621 break;
622 case 'helpbutton' :
623 $mform->setHelpButton($realelementname, $params);
624 break;
625 case 'disabledif' :
626 foreach ($namecloned as $num => $name){
627 if ($params[0] == $name){
628 $params[0] = $params[0]."[$i]";
629 break;
632 $params = array_merge(array($realelementname), $params);
633 call_user_func_array(array(&$mform, 'disabledIf'), $params);
634 break;
635 case 'rule' :
636 if (is_string($params)){
637 $params = array(null, $params, null, 'client');
639 $params = array_merge(array($realelementname), $params);
640 call_user_func_array(array(&$mform, 'addRule'), $params);
641 break;
647 $mform->addElement('submit', $addfieldsname, $addstring);
649 if (!$addbuttoninside) {
650 $mform->closeHeaderBefore($addfieldsname);
653 return $repeats;
657 * Adds a link/button that controls the checked state of a group of checkboxes.
658 * @param int $groupid The id of the group of advcheckboxes this element controls
659 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
660 * @param array $attributes associative array of HTML attributes
661 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
663 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
664 global $CFG;
666 // Set the default text if none was specified
667 if (empty($text)) {
668 $text = get_string('selectallornone', 'form');
671 $mform = $this->_form;
672 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
674 if ($select_value == 0 || is_null($select_value)) {
675 $new_select_value = 1;
676 } else {
677 $new_select_value = 0;
680 $mform->addElement('hidden', "checkbox_controller$groupid");
681 $mform->setType("checkbox_controller$groupid", PARAM_INT);
682 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
684 // Locate all checkboxes for this group and set their value, IF the optional param was given
685 if (!is_null($select_value)) {
686 foreach ($this->_form->_elements as $element) {
687 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
688 $mform->setConstants(array($element->getAttribute('name') => $select_value));
693 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
694 $mform->registerNoSubmitButton($checkbox_controller_name);
696 // Prepare Javascript for submit element
697 $js = "\n//<![CDATA[\n";
698 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
699 $js .= <<<EOS
700 function html_quickform_toggle_checkboxes(group) {
701 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
702 var newvalue = false;
703 var global = eval('html_quickform_checkboxgroup' + group + ';');
704 if (global == 1) {
705 eval('html_quickform_checkboxgroup' + group + ' = 0;');
706 newvalue = '';
707 } else {
708 eval('html_quickform_checkboxgroup' + group + ' = 1;');
709 newvalue = 'checked';
712 for (i = 0; i < checkboxes.length; i++) {
713 checkboxes[i].checked = newvalue;
716 EOS;
717 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
719 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
721 $js .= "//]]>\n";
723 require_once("$CFG->libdir/form/submitlink.php");
724 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
725 $submitlink->_js = $js;
726 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
727 $mform->addElement($submitlink);
728 $mform->setDefault($checkbox_controller_name, $text);
732 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
733 * if you don't want a cancel button in your form. If you have a cancel button make sure you
734 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
735 * get data with get_data().
737 * @param boolean $cancel whether to show cancel button, default true
738 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
740 function add_action_buttons($cancel = true, $submitlabel=null){
741 if (is_null($submitlabel)){
742 $submitlabel = get_string('savechanges');
744 $mform =& $this->_form;
745 if ($cancel){
746 //when two elements we need a group
747 $buttonarray=array();
748 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
749 $buttonarray[] = &$mform->createElement('cancel');
750 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
751 $mform->closeHeaderBefore('buttonar');
752 } else {
753 //no group needed
754 $mform->addElement('submit', 'submitbutton', $submitlabel);
755 $mform->closeHeaderBefore('submitbutton');
761 * You never extend this class directly. The class methods of this class are available from
762 * the private $this->_form property on moodleform and its children. You generally only
763 * call methods on this class from within abstract methods that you override on moodleform such
764 * as definition and definition_after_data
767 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
768 var $_types = array();
769 var $_dependencies = array();
771 * Array of buttons that if pressed do not result in the processing of the form.
773 * @var array
775 var $_noSubmitButtons=array();
777 * Array of buttons that if pressed do not result in the processing of the form.
779 * @var array
781 var $_cancelButtons=array();
784 * Array whose keys are element names. If the key exists this is a advanced element
786 * @var array
788 var $_advancedElements = array();
791 * Whether to display advanced elements (on page load)
793 * @var boolean
795 var $_showAdvanced = null;
798 * The form name is derrived from the class name of the wrapper minus the trailing form
799 * It is a name with words joined by underscores whereas the id attribute is words joined by
800 * underscores.
802 * @var unknown_type
804 var $_formName = '';
807 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
809 * @var string
811 var $_pageparams = '';
814 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
815 * @param string $formName Form's name.
816 * @param string $method (optional)Form's method defaults to 'POST'
817 * @param mixed $action (optional)Form's action - string or moodle_url
818 * @param string $target (optional)Form's target defaults to none
819 * @param mixed $attributes (optional)Extra attributes for <form> tag
820 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
821 * @access public
823 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
824 global $CFG;
826 static $formcounter = 1;
828 HTML_Common::HTML_Common($attributes);
829 $target = empty($target) ? array() : array('target' => $target);
830 $this->_formName = $formName;
831 if (is_a($action, 'moodle_url')){
832 $this->_pageparams = $action->hidden_params_out();
833 $action = $action->out(true);
834 } else {
835 $this->_pageparams = '';
837 //no 'name' atttribute for form in xhtml strict :
838 $attributes = array('action'=>$action, 'method'=>$method,
839 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
840 $formcounter++;
841 $this->updateAttributes($attributes);
843 //this is custom stuff for Moodle :
844 $oldclass= $this->getAttribute('class');
845 if (!empty($oldclass)){
846 $this->updateAttributes(array('class'=>$oldclass.' mform'));
847 }else {
848 $this->updateAttributes(array('class'=>'mform'));
850 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
851 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
852 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
853 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
857 * Use this method to indicate an element in a form is an advanced field. If items in a form
858 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
859 * form so the user can decide whether to display advanced form controls.
861 * If you set a header element to advanced then all elements it contains will also be set as advanced.
863 * @param string $elementName group or element name (not the element name of something inside a group).
864 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
866 function setAdvanced($elementName, $advanced=true){
867 if ($advanced){
868 $this->_advancedElements[$elementName]='';
869 } elseif (isset($this->_advancedElements[$elementName])) {
870 unset($this->_advancedElements[$elementName]);
872 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
873 $this->setShowAdvanced();
874 $this->registerNoSubmitButton('mform_showadvanced');
876 $this->addElement('hidden', 'mform_showadvanced_last');
877 $this->setType('mform_showadvanced_last', PARAM_INT);
881 * Set whether to show advanced elements in the form on first displaying form. Default is not to
882 * display advanced elements in the form until 'Show Advanced' is pressed.
884 * You can get the last state of the form and possibly save it for this user by using
885 * value 'mform_showadvanced_last' in submitted data.
887 * @param boolean $showadvancedNow
889 function setShowAdvanced($showadvancedNow = null){
890 if ($showadvancedNow === null){
891 if ($this->_showAdvanced !== null){
892 return;
893 } else { //if setShowAdvanced is called without any preference
894 //make the default to not show advanced elements.
895 $showadvancedNow = get_user_preferences(
896 moodle_strtolower($this->_formName.'_showadvanced', 0));
899 //value of hidden element
900 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
901 //value of button
902 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
903 //toggle if button pressed or else stay the same
904 if ($hiddenLast == -1) {
905 $next = $showadvancedNow;
906 } elseif ($buttonPressed) { //toggle on button press
907 $next = !$hiddenLast;
908 } else {
909 $next = $hiddenLast;
911 $this->_showAdvanced = $next;
912 if ($showadvancedNow != $next){
913 set_user_preference($this->_formName.'_showadvanced', $next);
915 $this->setConstants(array('mform_showadvanced_last'=>$next));
917 function getShowAdvanced(){
918 return $this->_showAdvanced;
923 * Accepts a renderer
925 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
926 * @since 3.0
927 * @access public
928 * @return void
930 function accept(&$renderer) {
931 if (method_exists($renderer, 'setAdvancedElements')){
932 //check for visible fieldsets where all elements are advanced
933 //and mark these headers as advanced as well.
934 //And mark all elements in a advanced header as advanced
935 $stopFields = $renderer->getStopFieldSetElements();
936 $lastHeader = null;
937 $lastHeaderAdvanced = false;
938 $anyAdvanced = false;
939 foreach (array_keys($this->_elements) as $elementIndex){
940 $element =& $this->_elements[$elementIndex];
942 // if closing header and any contained element was advanced then mark it as advanced
943 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
944 if ($anyAdvanced && !is_null($lastHeader)){
945 $this->setAdvanced($lastHeader->getName());
947 $lastHeaderAdvanced = false;
948 unset($lastHeader);
949 $lastHeader = null;
950 } elseif ($lastHeaderAdvanced) {
951 $this->setAdvanced($element->getName());
954 if ($element->getType()=='header'){
955 $lastHeader =& $element;
956 $anyAdvanced = false;
957 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
958 } elseif (isset($this->_advancedElements[$element->getName()])){
959 $anyAdvanced = true;
962 // the last header may not be closed yet...
963 if ($anyAdvanced && !is_null($lastHeader)){
964 $this->setAdvanced($lastHeader->getName());
966 $renderer->setAdvancedElements($this->_advancedElements);
969 parent::accept($renderer);
974 function closeHeaderBefore($elementName){
975 $renderer =& $this->defaultRenderer();
976 $renderer->addStopFieldsetElements($elementName);
980 * Should be used for all elements of a form except for select, radio and checkboxes which
981 * clean their own data.
983 * @param string $elementname
984 * @param integer $paramtype use the constants PARAM_*.
985 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
986 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
987 * It will strip all html tags. But will still let tags for multilang support
988 * through.
989 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
990 * html editor. Data from the editor is later cleaned before display using
991 * format_text() function. PARAM_RAW can also be used for data that is validated
992 * by some other way or printed by p() or s().
993 * * PARAM_INT should be used for integers.
994 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
995 * form actions.
997 function setType($elementname, $paramtype) {
998 $this->_types[$elementname] = $paramtype;
1002 * See description of setType above. This can be used to set several types at once.
1004 * @param array $paramtypes
1006 function setTypes($paramtypes) {
1007 $this->_types = $paramtypes + $this->_types;
1010 function updateSubmission($submission, $files) {
1011 $this->_flagSubmitted = false;
1013 if (empty($submission)) {
1014 $this->_submitValues = array();
1015 } else {
1016 foreach ($submission as $key=>$s) {
1017 if (array_key_exists($key, $this->_types)) {
1018 $submission[$key] = clean_param($s, $this->_types[$key]);
1021 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
1022 $this->_flagSubmitted = true;
1025 if (empty($files)) {
1026 $this->_submitFiles = array();
1027 } else {
1028 if (1 == get_magic_quotes_gpc()) {
1029 foreach (array_keys($files) as $elname) {
1030 // dangerous characters in filenames are cleaned later in upload_manager
1031 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
1034 $this->_submitFiles = $files;
1035 $this->_flagSubmitted = true;
1038 // need to tell all elements that they need to update their value attribute.
1039 foreach (array_keys($this->_elements) as $key) {
1040 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1044 function getReqHTML(){
1045 return $this->_reqHTML;
1048 function getAdvancedHTML(){
1049 return $this->_advancedHTML;
1053 * Initializes a default form value. Used to specify the default for a new entry where
1054 * no data is loaded in using moodleform::set_data()
1056 * @param string $elementname element name
1057 * @param mixed $values values for that element name
1058 * @param bool $slashed the default value is slashed
1059 * @access public
1060 * @return void
1062 function setDefault($elementName, $defaultValue, $slashed=false){
1063 $filter = $slashed ? 'stripslashes' : NULL;
1064 $this->setDefaults(array($elementName=>$defaultValue), $filter);
1065 } // end func setDefault
1067 * Add an array of buttons to the form
1068 * @param array $buttons An associative array representing help button to attach to
1069 * to the form. keys of array correspond to names of elements in form.
1071 * @access public
1073 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1075 foreach ($buttons as $elementname => $button){
1076 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1080 * Add a single button.
1082 * @param string $elementname name of the element to add the item to
1083 * @param array $button - arguments to pass to function $function
1084 * @param boolean $suppresscheck - whether to throw an error if the element
1085 * doesn't exist.
1086 * @param string $function - function to generate html from the arguments in $button
1088 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
1089 if (array_key_exists($elementname, $this->_elementIndex)){
1090 //_elements has a numeric index, this code accesses the elements by name
1091 $element=&$this->_elements[$this->_elementIndex[$elementname]];
1092 if (method_exists($element, 'setHelpButton')){
1093 $element->setHelpButton($button, $function);
1094 }else{
1095 $a=new object();
1096 $a->name=$element->getName();
1097 $a->classname=get_class($element);
1098 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
1100 }elseif (!$suppresscheck){
1101 print_error('nonexistentformelements', 'form', '', $elementname);
1106 * Set constant value not overriden by _POST or _GET
1107 * note: this does not work for complex names with [] :-(
1108 * @param string $elname name of element
1109 * @param mixed $value
1110 * @return void
1112 function setConstant($elname, $value) {
1113 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1114 $element =& $this->getElement($elname);
1115 $element->onQuickFormEvent('updateValue', null, $this);
1118 function exportValues($elementList= null, $addslashes=true){
1119 $unfiltered = array();
1120 if (null === $elementList) {
1121 // iterate over all elements, calling their exportValue() methods
1122 $emptyarray = array();
1123 foreach (array_keys($this->_elements) as $key) {
1124 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1125 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1126 } else {
1127 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1130 if (is_array($value)) {
1131 // This shit throws a bogus warning in PHP 4.3.x
1132 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1135 } else {
1136 if (!is_array($elementList)) {
1137 $elementList = array_map('trim', explode(',', $elementList));
1139 foreach ($elementList as $elementName) {
1140 $value = $this->exportValue($elementName);
1141 if (PEAR::isError($value)) {
1142 return $value;
1144 $unfiltered[$elementName] = $value;
1148 if (is_array($this->_constantValues)) {
1149 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1152 if ($addslashes){
1153 return $this->_recursiveFilter('addslashes', $unfiltered);
1154 } else {
1155 return $unfiltered;
1159 * Adds a validation rule for the given field
1161 * If the element is in fact a group, it will be considered as a whole.
1162 * To validate grouped elements as separated entities,
1163 * use addGroupRule instead of addRule.
1165 * @param string $element Form element name
1166 * @param string $message Message to display for invalid data
1167 * @param string $type Rule type, use getRegisteredRules() to get types
1168 * @param string $format (optional)Required for extra rule data
1169 * @param string $validation (optional)Where to perform validation: "server", "client"
1170 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1171 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1172 * @since 1.0
1173 * @access public
1174 * @throws HTML_QuickForm_Error
1176 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1178 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1179 if ($validation == 'client') {
1180 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1183 } // end func addRule
1185 * Adds a validation rule for the given group of elements
1187 * Only groups with a name can be assigned a validation rule
1188 * Use addGroupRule when you need to validate elements inside the group.
1189 * Use addRule if you need to validate the group as a whole. In this case,
1190 * the same rule will be applied to all elements in the group.
1191 * Use addRule if you need to validate the group against a function.
1193 * @param string $group Form group name
1194 * @param mixed $arg1 Array for multiple elements or error message string for one element
1195 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1196 * @param string $format (optional)Required for extra rule data
1197 * @param int $howmany (optional)How many valid elements should be in the group
1198 * @param string $validation (optional)Where to perform validation: "server", "client"
1199 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1200 * @since 2.5
1201 * @access public
1202 * @throws HTML_QuickForm_Error
1204 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1206 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1207 if (is_array($arg1)) {
1208 foreach ($arg1 as $rules) {
1209 foreach ($rules as $rule) {
1210 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1212 if ('client' == $validation) {
1213 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1217 } elseif (is_string($arg1)) {
1219 if ($validation == 'client') {
1220 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1223 } // end func addGroupRule
1225 // }}}
1227 * Returns the client side validation script
1229 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1230 * and slightly modified to run rules per-element
1231 * Needed to override this because of an error with client side validation of grouped elements.
1233 * @access public
1234 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1236 function getValidationScript()
1238 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1239 return '';
1242 include_once('HTML/QuickForm/RuleRegistry.php');
1243 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1244 $test = array();
1245 $js_escape = array(
1246 "\r" => '\r',
1247 "\n" => '\n',
1248 "\t" => '\t',
1249 "'" => "\\'",
1250 '"' => '\"',
1251 '\\' => '\\\\'
1254 foreach ($this->_rules as $elementName => $rules) {
1255 foreach ($rules as $rule) {
1256 if ('client' == $rule['validation']) {
1257 unset($element); //TODO: find out how to properly initialize it
1259 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1260 $rule['message'] = strtr($rule['message'], $js_escape);
1262 if (isset($rule['group'])) {
1263 $group =& $this->getElement($rule['group']);
1264 // No JavaScript validation for frozen elements
1265 if ($group->isFrozen()) {
1266 continue 2;
1268 $elements =& $group->getElements();
1269 foreach (array_keys($elements) as $key) {
1270 if ($elementName == $group->getElementName($key)) {
1271 $element =& $elements[$key];
1272 break;
1275 } elseif ($dependent) {
1276 $element = array();
1277 $element[] =& $this->getElement($elementName);
1278 foreach ($rule['dependent'] as $elName) {
1279 $element[] =& $this->getElement($elName);
1281 } else {
1282 $element =& $this->getElement($elementName);
1284 // No JavaScript validation for frozen elements
1285 if (is_object($element) && $element->isFrozen()) {
1286 continue 2;
1287 } elseif (is_array($element)) {
1288 foreach (array_keys($element) as $key) {
1289 if ($element[$key]->isFrozen()) {
1290 continue 3;
1294 // Fix for bug displaying errors for elements in a group
1295 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1296 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1297 $test[$elementName][1]=$element;
1298 //end of fix
1303 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1304 // the form, and then that form field gets corrupted by the code that follows.
1305 unset($element);
1307 $js = '
1308 <script type="text/javascript">
1309 //<![CDATA[
1311 var skipClientValidation = false;
1313 function qf_errorHandler(element, _qfMsg) {
1314 div = element.parentNode;
1315 if (_qfMsg != \'\') {
1316 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1317 if (!errorSpan) {
1318 errorSpan = document.createElement("span");
1319 errorSpan.id = \'id_error_\'+element.name;
1320 errorSpan.className = "error";
1321 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1324 while (errorSpan.firstChild) {
1325 errorSpan.removeChild(errorSpan.firstChild);
1328 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1329 errorSpan.appendChild(document.createElement("br"));
1331 if (div.className.substr(div.className.length - 6, 6) != " error"
1332 && div.className != "error") {
1333 div.className += " error";
1336 return false;
1337 } else {
1338 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1339 if (errorSpan) {
1340 errorSpan.parentNode.removeChild(errorSpan);
1343 if (div.className.substr(div.className.length - 6, 6) == " error") {
1344 div.className = div.className.substr(0, div.className.length - 6);
1345 } else if (div.className == "error") {
1346 div.className = "";
1349 return true;
1352 $validateJS = '';
1353 foreach ($test as $elementName => $jsandelement) {
1354 // Fix for bug displaying errors for elements in a group
1355 //unset($element);
1356 list($jsArr,$element)=$jsandelement;
1357 //end of fix
1358 $escapedElementName = preg_replace_callback(
1359 '/[_\[\]]/',
1360 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1361 $elementName);
1362 $js .= '
1363 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1364 var value = \'\';
1365 var errFlag = new Array();
1366 var _qfGroups = {};
1367 var _qfMsg = \'\';
1368 var frm = element.parentNode;
1369 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1370 frm = frm.parentNode;
1372 ' . join("\n", $jsArr) . '
1373 return qf_errorHandler(element, _qfMsg);
1376 $validateJS .= '
1377 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1378 if (!ret && !first_focus) {
1379 first_focus = true;
1380 frm.elements[\''.$elementName.'\'].focus();
1384 // Fix for bug displaying errors for elements in a group
1385 //unset($element);
1386 //$element =& $this->getElement($elementName);
1387 //end of fix
1388 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1389 $onBlur = $element->getAttribute('onBlur');
1390 $onChange = $element->getAttribute('onChange');
1391 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1392 'onChange' => $onChange . $valFunc));
1394 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1395 $js .= '
1396 function validate_' . $this->_formName . '(frm) {
1397 if (skipClientValidation) {
1398 return true;
1400 var ret = true;
1402 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1403 var first_focus = false;
1404 ' . $validateJS . ';
1405 return ret;
1407 //]]>
1408 </script>';
1409 return $js;
1410 } // end func getValidationScript
1411 function _setDefaultRuleMessages(){
1412 foreach ($this->_rules as $field => $rulesarr){
1413 foreach ($rulesarr as $key => $rule){
1414 if ($rule['message']===null){
1415 $a=new object();
1416 $a->format=$rule['format'];
1417 $str=get_string('err_'.$rule['type'], 'form', $a);
1418 if (strpos($str, '[[')!==0){
1419 $this->_rules[$field][$key]['message']=$str;
1426 function getLockOptionEndScript(){
1428 $iname = $this->getAttribute('id').'items';
1429 $js = '<script type="text/javascript">'."\n";
1430 $js .= '//<![CDATA['."\n";
1431 $js .= "var $iname = Array();\n";
1433 foreach ($this->_dependencies as $dependentOn => $conditions){
1434 $js .= "{$iname}['$dependentOn'] = Array();\n";
1435 foreach ($conditions as $condition=>$values) {
1436 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1437 foreach ($values as $value=>$dependents) {
1438 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1439 $i = 0;
1440 foreach ($dependents as $dependent) {
1441 $elements = $this->_getElNamesRecursive($dependent);
1442 if (empty($elements)) {
1443 // probably element inside of some group
1444 $elements = array($dependent);
1446 foreach($elements as $element) {
1447 if ($element == $dependentOn) {
1448 continue;
1450 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1451 $i++;
1457 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1458 $js .='//]]>'."\n";
1459 $js .='</script>'."\n";
1460 return $js;
1463 function _getElNamesRecursive($element) {
1464 if (is_string($element)) {
1465 if (!$this->elementExists($element)) {
1466 return array();
1468 $element = $this->getElement($element);
1471 if (is_a($element, 'HTML_QuickForm_group')) {
1472 $elsInGroup = $element->getElements();
1473 $elNames = array();
1474 foreach ($elsInGroup as $elInGroup){
1475 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1476 // not sure if this would work - groups nested in groups
1477 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1478 } else {
1479 $elNames[] = $element->getElementName($elInGroup->getName());
1483 } else if (is_a($element, 'HTML_QuickForm_header')) {
1484 return array();
1486 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1487 return array();
1489 } else if (method_exists($element, 'getPrivateName')) {
1490 return array($element->getPrivateName());
1492 } else {
1493 $elNames = array($element->getName());
1496 return $elNames;
1500 * Adds a dependency for $elementName which will be disabled if $condition is met.
1501 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1502 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1503 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1504 * of the $dependentOn element is $condition (such as equal) to $value.
1506 * @param string $elementName the name of the element which will be disabled
1507 * @param string $dependentOn the name of the element whose state will be checked for
1508 * condition
1509 * @param string $condition the condition to check
1510 * @param mixed $value used in conjunction with condition.
1512 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1513 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1514 $this->_dependencies[$dependentOn] = array();
1516 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1517 $this->_dependencies[$dependentOn][$condition] = array();
1519 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1520 $this->_dependencies[$dependentOn][$condition][$value] = array();
1522 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1525 function registerNoSubmitButton($buttonname){
1526 $this->_noSubmitButtons[]=$buttonname;
1529 function isNoSubmitButton($buttonname){
1530 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1533 function _registerCancelButton($addfieldsname){
1534 $this->_cancelButtons[]=$addfieldsname;
1537 * Displays elements without HTML input tags.
1538 * This method is different to freeze() in that it makes sure no hidden
1539 * elements are included in the form.
1540 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1542 * This function also removes all previously defined rules.
1544 * @param mixed $elementList array or string of element(s) to be frozen
1545 * @since 1.0
1546 * @access public
1547 * @throws HTML_QuickForm_Error
1549 function hardFreeze($elementList=null)
1551 if (!isset($elementList)) {
1552 $this->_freezeAll = true;
1553 $elementList = array();
1554 } else {
1555 if (!is_array($elementList)) {
1556 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1558 $elementList = array_flip($elementList);
1561 foreach (array_keys($this->_elements) as $key) {
1562 $name = $this->_elements[$key]->getName();
1563 if ($this->_freezeAll || isset($elementList[$name])) {
1564 $this->_elements[$key]->freeze();
1565 $this->_elements[$key]->setPersistantFreeze(false);
1566 unset($elementList[$name]);
1568 // remove all rules
1569 $this->_rules[$name] = array();
1570 // if field is required, remove the rule
1571 $unset = array_search($name, $this->_required);
1572 if ($unset !== false) {
1573 unset($this->_required[$unset]);
1578 if (!empty($elementList)) {
1579 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);
1581 return true;
1584 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1586 * This function also removes all previously defined rules of elements it freezes.
1588 * @param array $elementList array or string of element(s) not to be frozen
1589 * @since 1.0
1590 * @access public
1591 * @throws HTML_QuickForm_Error
1593 function hardFreezeAllVisibleExcept($elementList)
1595 $elementList = array_flip($elementList);
1596 foreach (array_keys($this->_elements) as $key) {
1597 $name = $this->_elements[$key]->getName();
1598 $type = $this->_elements[$key]->getType();
1600 if ($type == 'hidden'){
1601 // leave hidden types as they are
1602 } elseif (!isset($elementList[$name])) {
1603 $this->_elements[$key]->freeze();
1604 $this->_elements[$key]->setPersistantFreeze(false);
1606 // remove all rules
1607 $this->_rules[$name] = array();
1608 // if field is required, remove the rule
1609 $unset = array_search($name, $this->_required);
1610 if ($unset !== false) {
1611 unset($this->_required[$unset]);
1615 return true;
1618 * Tells whether the form was already submitted
1620 * This is useful since the _submitFiles and _submitValues arrays
1621 * may be completely empty after the trackSubmit value is removed.
1623 * @access public
1624 * @return bool
1626 function isSubmitted()
1628 return parent::isSubmitted() && (!$this->isFrozen());
1634 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1635 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1637 * Stylesheet is part of standard theme and should be automatically included.
1639 * @author Jamie Pratt <me@jamiep.org>
1640 * @license gpl license
1642 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1645 * Element template array
1646 * @var array
1647 * @access private
1649 var $_elementTemplates;
1651 * Template used when opening a hidden fieldset
1652 * (i.e. a fieldset that is opened when there is no header element)
1653 * @var string
1654 * @access private
1656 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1658 * Header Template string
1659 * @var string
1660 * @access private
1662 var $_headerTemplate =
1663 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1666 * Template used when opening a fieldset
1667 * @var string
1668 * @access private
1670 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1673 * Template used when closing a fieldset
1674 * @var string
1675 * @access private
1677 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1680 * Required Note template string
1681 * @var string
1682 * @access private
1684 var $_requiredNoteTemplate =
1685 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1687 var $_advancedElements = array();
1690 * Whether to display advanced elements (on page load)
1692 * @var integer 1 means show 0 means hide
1694 var $_showAdvanced;
1696 function MoodleQuickForm_Renderer(){
1697 // switch next two lines for ol li containers for form items.
1698 // $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>');
1699 $this->_elementTemplates = array(
1700 '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>',
1702 '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>',
1704 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}&nbsp;</div></div>',
1706 'nodisplay'=>'');
1708 parent::HTML_QuickForm_Renderer_Tableless();
1711 function setAdvancedElements($elements){
1712 $this->_advancedElements = $elements;
1716 * What to do when starting the form
1718 * @param MoodleQuickForm $form
1720 function startForm(&$form){
1721 $this->_reqHTML = $form->getReqHTML();
1722 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1723 $this->_advancedHTML = $form->getAdvancedHTML();
1724 $this->_showAdvanced = $form->getShowAdvanced();
1725 parent::startForm($form);
1726 if ($form->isFrozen()){
1727 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
1728 } else {
1729 $this->_hiddenHtml .= $form->_pageparams;
1735 function startGroup(&$group, $required, $error){
1736 if (method_exists($group, 'getElementTemplateType')){
1737 $html = $this->_elementTemplates[$group->getElementTemplateType()];
1738 }else{
1739 $html = $this->_elementTemplates['default'];
1742 if ($this->_showAdvanced){
1743 $advclass = ' advanced';
1744 } else {
1745 $advclass = ' advanced hide';
1747 if (isset($this->_advancedElements[$group->getName()])){
1748 $html =str_replace(' {advanced}', $advclass, $html);
1749 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1750 } else {
1751 $html =str_replace(' {advanced}', '', $html);
1752 $html =str_replace('{advancedimg}', '', $html);
1754 if (method_exists($group, 'getHelpButton')){
1755 $html =str_replace('{help}', $group->getHelpButton(), $html);
1756 }else{
1757 $html =str_replace('{help}', '', $html);
1759 $html =str_replace('{name}', $group->getName(), $html);
1760 $html =str_replace('{type}', 'fgroup', $html);
1762 $this->_templates[$group->getName()]=$html;
1763 // Fix for bug in tableless quickforms that didn't allow you to stop a
1764 // fieldset before a group of elements.
1765 // if the element name indicates the end of a fieldset, close the fieldset
1766 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1767 && $this->_fieldsetsOpen > 0
1769 $this->_html .= $this->_closeFieldsetTemplate;
1770 $this->_fieldsetsOpen--;
1772 parent::startGroup($group, $required, $error);
1775 function renderElement(&$element, $required, $error){
1776 //manipulate id of all elements before rendering
1777 if (!is_null($element->getAttribute('id'))) {
1778 $id = $element->getAttribute('id');
1779 } else {
1780 $id = $element->getName();
1782 //strip qf_ prefix and replace '[' with '_' and strip ']'
1783 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1784 if (strpos($id, 'id_') !== 0){
1785 $element->updateAttributes(array('id'=>'id_'.$id));
1788 //adding stuff to place holders in template
1789 if (method_exists($element, 'getElementTemplateType')){
1790 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1791 }else{
1792 $html = $this->_elementTemplates['default'];
1794 if ($this->_showAdvanced){
1795 $advclass = ' advanced';
1796 } else {
1797 $advclass = ' advanced hide';
1799 if (isset($this->_advancedElements[$element->getName()])){
1800 $html =str_replace(' {advanced}', $advclass, $html);
1801 } else {
1802 $html =str_replace(' {advanced}', '', $html);
1804 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1805 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1806 } else {
1807 $html =str_replace('{advancedimg}', '', $html);
1809 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1810 $html =str_replace('{name}', $element->getName(), $html);
1811 if (method_exists($element, 'getHelpButton')){
1812 $html = str_replace('{help}', $element->getHelpButton(), $html);
1813 }else{
1814 $html = str_replace('{help}', '', $html);
1817 if (!isset($this->_templates[$element->getName()])) {
1818 $this->_templates[$element->getName()] = $html;
1821 parent::renderElement($element, $required, $error);
1824 function finishForm(&$form){
1825 if ($form->isFrozen()){
1826 $this->_hiddenHtml = '';
1828 parent::finishForm($form);
1829 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1830 // add a lockoptions script
1831 $this->_html = $this->_html . "\n" . $script;
1835 * Called when visiting a header element
1837 * @param object An HTML_QuickForm_header element being visited
1838 * @access public
1839 * @return void
1841 function renderHeader(&$header) {
1842 $name = $header->getName();
1844 $id = empty($name) ? '' : ' id="' . $name . '"';
1845 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1846 if (is_null($header->_text)) {
1847 $header_html = '';
1848 } elseif (!empty($name) && isset($this->_templates[$name])) {
1849 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1850 } else {
1851 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1854 if (isset($this->_advancedElements[$name])){
1855 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1856 } else {
1857 $header_html =str_replace('{advancedimg}', '', $header_html);
1859 $elementName='mform_showadvanced';
1860 if ($this->_showAdvanced==0){
1861 $buttonlabel = get_string('showadvanced', 'form');
1862 } else {
1863 $buttonlabel = get_string('hideadvanced', 'form');
1866 if (isset($this->_advancedElements[$name])){
1867 require_js(array('yui_yahoo', 'yui_event'));
1868 // this is tricky - the first submit button on form is "clicked" if user presses enter
1869 // we do not want to "submit" using advanced button if javascript active
1870 $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />';
1872 $buttonlabel = addslashes_js($buttonlabel);
1873 $showtext = addslashes_js(get_string('showadvanced', 'form'));
1874 $hidetext = addslashes_js(get_string('hideadvanced', 'form'));
1875 $button = '<script id="' . $name . '_script" type="text/javascript">' . "
1876 showAdvancedInit('{$name}_script', '$elementName', '$buttonlabel', '$hidetext', '$showtext');
1877 " . '</script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation
1879 $header_html = str_replace('{button}', $button, $header_html);
1880 } else {
1881 $header_html = str_replace('{button}', '', $header_html);
1884 if ($this->_fieldsetsOpen > 0) {
1885 $this->_html .= $this->_closeFieldsetTemplate;
1886 $this->_fieldsetsOpen--;
1889 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1890 if ($this->_showAdvanced){
1891 $advclass = ' class="advanced"';
1892 } else {
1893 $advclass = ' class="advanced hide"';
1895 if (isset($this->_advancedElements[$name])){
1896 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1897 } else {
1898 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1900 $this->_html .= $openFieldsetTemplate . $header_html;
1901 $this->_fieldsetsOpen++;
1902 } // end func renderHeader
1904 function getStopFieldsetElements(){
1905 return $this->_stopFieldsetElements;
1910 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1912 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1913 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1914 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1915 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1916 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1917 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1918 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1919 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1920 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
1921 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1922 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1923 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1924 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1925 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1926 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1927 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1928 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1929 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1930 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1931 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1932 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1933 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1934 MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1935 MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1936 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1937 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1938 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1939 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
1940 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
1941 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');