MDL-12296:
[moodle-linuxchix.git] / lib / formslib.php
blobf4285da203f3474378b86f0bce5633989926010d
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 * @version $Id$
21 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
24 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else.
25 if (FALSE===strstr(ini_get('include_path'), $CFG->libdir.'/pear' )){
26 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
28 require_once 'HTML/QuickForm.php';
29 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
30 require_once 'HTML/QuickForm/Renderer/Tableless.php';
32 require_once $CFG->libdir.'/uploadlib.php';
34 /**
35 * Callback called when PEAR throws an error
37 * @param PEAR_Error $error
39 function pear_handle_error($error){
40 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
41 echo '<br /> <strong>Backtrace </strong>:';
42 print_object($error->backtrace);
45 if ($CFG->debug >= DEBUG_ALL){
46 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
50 /**
51 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
52 * use this class you should write a class defintion which extends this class or a more specific
53 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
55 * You will write your own definition() method which performs the form set up.
57 class moodleform {
58 var $_formname; // form name
59 /**
60 * quickform object definition
62 * @var MoodleQuickForm
64 var $_form;
65 /**
66 * globals workaround
68 * @var array
70 var $_customdata;
71 /**
72 * file upload manager
74 * @var upload_manager
76 var $_upload_manager; //
77 /**
78 * definition_after_data executed flag
79 * @var definition_finalized
81 var $_definition_finalized = false;
83 /**
84 * The constructor function calls the abstract function definition() and it will then
85 * process and clean and attempt to validate incoming data.
87 * It will call your custom validate method to validate data and will also check any rules
88 * you have specified in definition using addRule
90 * The name of the form (id attribute of the form) is automatically generated depending on
91 * the name you gave the class extending moodleform. You should call your class something
92 * like
94 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
95 * current url. If a moodle_url object then outputs params as hidden variables.
96 * @param array $customdata if your form defintion method needs access to data such as $course
97 * $cm, etc. to construct the form definition then pass it in this array. You can
98 * use globals for somethings.
99 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
100 * be merged and used as incoming data to the form.
101 * @param string $target target frame for form submission. You will rarely use this. Don't use
102 * it if you don't need to as the target attribute is deprecated in xhtml
103 * strict.
104 * @param mixed $attributes you can pass a string of html attributes here or an array.
105 * @return moodleform
107 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
108 if (empty($action)){
109 $action = strip_querystring(qualified_me());
112 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
113 $this->_customdata = $customdata;
114 $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
115 if (!$editable){
116 $this->_form->hardFreeze();
118 $this->set_upload_manager(new upload_manager());
120 $this->definition();
122 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
123 $this->_form->setDefault('sesskey', sesskey());
124 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
125 $this->_form->setDefault('_qf__'.$this->_formname, 1);
126 $this->_form->_setDefaultRuleMessages();
128 // we have to know all input types before processing submission ;-)
129 $this->_process_submission($method);
133 * To autofocus on first form element or first element with error.
135 * @param string $name if this is set then the focus is forced to a field with this name
137 * @return string javascript to select form element with first error or
138 * first element if no errors. Use this as a parameter
139 * when calling print_header
141 function focus($name=NULL) {
142 $form =& $this->_form;
143 $elkeys = array_keys($form->_elementIndex);
144 $error = false;
145 if (isset($form->_errors) && 0 != count($form->_errors)){
146 $errorkeys = array_keys($form->_errors);
147 $elkeys = array_intersect($elkeys, $errorkeys);
148 $error = true;
151 if ($error or empty($name)) {
152 $names = array();
153 while (empty($names) and !empty($elkeys)) {
154 $el = array_shift($elkeys);
155 $names = $form->_getElNamesRecursive($el);
157 if (!empty($names)) {
158 $name = array_shift($names);
162 $focus = '';
163 if (!empty($name)) {
164 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
167 return $focus;
171 * Internal method. Alters submitted data to be suitable for quickforms processing.
172 * Must be called when the form is fully set up.
174 function _process_submission($method) {
175 $submission = array();
176 if ($method == 'post') {
177 if (!empty($_POST)) {
178 $submission = $_POST;
180 } else {
181 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
184 // following trick is needed to enable proper sesskey checks when using GET forms
185 // the _qf__.$this->_formname serves as a marker that form was actually submitted
186 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
187 if (!confirm_sesskey()) {
188 error('Incorrect sesskey submitted, form not accepted!');
190 $files = $_FILES;
191 } else {
192 $submission = array();
193 $files = array();
196 $this->_form->updateSubmission($submission, $files);
200 * Internal method. Validates all uploaded files.
202 function _validate_files(&$files) {
203 $files = array();
205 if (empty($_FILES)) {
206 // we do not need to do any checks because no files were submitted
207 // note: server side rules do not work for files - use custom verification in validate() instead
208 return true;
210 $errors = array();
211 $mform =& $this->_form;
213 // check the files
214 $status = $this->_upload_manager->preprocess_files();
216 // now check that we really want each file
217 foreach ($_FILES as $elname=>$file) {
218 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
219 $required = $mform->isElementRequired($elname);
220 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
221 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
222 // file not uploaded and not required - ignore it
223 continue;
225 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
227 } else if (!empty($this->_upload_manager->files[$elname]['clear'])) {
228 $files[$elname] = $this->_upload_manager->files[$elname]['tmp_name'];
230 } else {
231 error('Incorrect upload attempt!');
235 // return errors if found
236 if ($status and 0 == count($errors)){
237 return true;
239 } else {
240 $files = array();
241 return $errors;
246 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
247 * form definition (new entry form); this function is used to load in data where values
248 * already exist and data is being edited (edit entry form).
250 * @param mixed $default_values object or array of default values
251 * @param bool $slased true if magic quotes applied to data values
253 function set_data($default_values, $slashed=false) {
254 if (is_object($default_values)) {
255 $default_values = (array)$default_values;
257 $filter = $slashed ? 'stripslashes' : NULL;
258 $this->_form->setDefaults($default_values, $filter);
262 * Set custom upload manager.
263 * Must be used BEFORE creating of file element!
265 * @param object $um - custom upload manager
267 function set_upload_manager($um=false) {
268 if ($um === false) {
269 $um = new upload_manager();
271 $this->_upload_manager = $um;
273 $this->_form->setMaxFileSize($um->config->maxbytes);
277 * Check that form was submitted. Does not check validity of submitted data.
279 * @return bool true if form properly submitted
281 function is_submitted() {
282 return $this->_form->isSubmitted();
285 function no_submit_button_pressed(){
286 static $nosubmit = null; // one check is enough
287 if (!is_null($nosubmit)){
288 return $nosubmit;
290 $mform =& $this->_form;
291 $nosubmit = false;
292 if (!$this->is_submitted()){
293 return false;
295 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
296 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
297 $nosubmit = true;
298 break;
301 return $nosubmit;
306 * Check that form data is valid.
308 * @return bool true if form data valid
310 function is_validated() {
311 static $validated = null; // one validation is enough
312 $mform =& $this->_form;
314 //finalize the form definition before any processing
315 if (!$this->_definition_finalized) {
316 $this->_definition_finalized = true;
317 $this->definition_after_data();
320 if ($this->no_submit_button_pressed()){
321 return false;
322 } elseif ($validated === null) {
323 $internal_val = $mform->validate();
325 $files = array();
326 $file_val = $this->_validate_files($files);
327 if ($file_val !== true) {
328 if (!empty($file_val)) {
329 foreach ($file_val as $element=>$msg) {
330 $mform->setElementError($element, $msg);
333 $file_val = false;
336 $data = $mform->exportValues(null, true);
337 $moodle_val = $this->validation($data, $files);
338 if ($moodle_val !== true) {
339 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
340 foreach ($moodle_val as $element=>$msg) {
341 $mform->setElementError($element, $msg);
343 $moodle_val = false;
344 } else {
345 $moodle_val = true;
349 $validated = ($internal_val and $moodle_val and $file_val);
351 return $validated;
355 * Return true if a cancel button has been pressed resulting in the form being submitted.
357 * @return boolean true if a cancel button has been pressed
359 function is_cancelled(){
360 $mform =& $this->_form;
361 if ($mform->isSubmitted()){
362 foreach ($mform->_cancelButtons as $cancelbutton){
363 if (optional_param($cancelbutton, 0, PARAM_RAW)){
364 return true;
368 return false;
372 * Return submitted data if properly submitted or returns NULL if validation fails or
373 * if there is no submitted data.
375 * @param bool $slashed true means return data with addslashes applied
376 * @return object submitted data; NULL if not valid or not submitted
378 function get_data($slashed=true) {
379 $mform =& $this->_form;
381 if ($this->is_submitted() and $this->is_validated()) {
382 $data = $mform->exportValues(null, $slashed);
383 unset($data['sesskey']); // we do not need to return sesskey
384 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
385 if (empty($data)) {
386 return NULL;
387 } else {
388 return (object)$data;
390 } else {
391 return NULL;
396 * Return submitted data without validation or NULL if there is no submitted data.
398 * @param bool $slashed true means return data with addslashes applied
399 * @return object submitted data; NULL if not submitted
401 function get_submitted_data($slashed=true) {
402 $mform =& $this->_form;
404 if ($this->is_submitted()) {
405 $data = $mform->exportValues(null, $slashed);
406 unset($data['sesskey']); // we do not need to return sesskey
407 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
408 if (empty($data)) {
409 return NULL;
410 } else {
411 return (object)$data;
413 } else {
414 return NULL;
419 * Save verified uploaded files into directory. Upload process can be customised from definition()
420 * method by creating instance of upload manager and storing it in $this->_upload_form
422 * @param string $destination where to store uploaded files
423 * @return bool success
425 function save_files($destination) {
426 if ($this->is_submitted() and $this->is_validated()) {
427 return $this->_upload_manager->save_files($destination);
429 return false;
433 * If we're only handling one file (if inputname was given in the constructor)
434 * this will return the (possibly changed) filename of the file.
435 * @return mixed false in case of failure, string if ok
437 function get_new_filename() {
438 return $this->_upload_manager->get_new_filename();
442 * Get content of uploaded file.
443 * @param $element name of file upload element
444 * @return mixed false in case of failure, string if ok
446 function get_file_content($elname) {
447 if (!$this->is_submitted() or !$this->is_validated()) {
448 return false;
451 if (!$this->_form->elementExists($elname)) {
452 return false;
455 if (empty($this->_upload_manager->files[$elname]['clear'])) {
456 return false;
459 if (empty($this->_upload_manager->files[$elname]['tmp_name'])) {
460 return false;
463 $data = "";
464 $file = @fopen($this->_upload_manager->files[$elname]['tmp_name'], "rb");
465 if ($file) {
466 while (!feof($file)) {
467 $data .= fread($file, 1024); // TODO: do we really have to do this?
469 fclose($file);
470 return $data;
471 } else {
472 return false;
477 * Print html form.
479 function display() {
480 //finalize the form definition if not yet done
481 if (!$this->_definition_finalized) {
482 $this->_definition_finalized = true;
483 $this->definition_after_data();
485 $this->_form->display();
489 * Abstract method - always override!
491 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
493 function definition() {
494 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
498 * Dummy stub method - override if you need to setup the form depending on current
499 * values. This method is called after definition(), data submission and set_data().
500 * All form setup that is dependent on form values should go in here.
502 function definition_after_data(){
506 * Dummy stub method - override if you needed to perform some extra validation.
507 * If there are errors return array of errors ("fieldname"=>"error message"),
508 * otherwise true if ok.
510 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
512 * @param array $data array of ("fieldname"=>value) of submitted data
513 * @param array $files array of uploaded files "element_name"=>tmp_file_path
514 * @return mixed an array of "element_name"=>"error_description" if there are errors.
515 * true or an empty array if everything is OK.
517 function validation($data, $files) {
518 return array();
522 * Method to add a repeating group of elements to a form.
524 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
525 * @param integer $repeats no of times to repeat elements initially
526 * @param array $options Array of options to apply to elements. Array keys are element names.
527 * This is an array of arrays. The second sets of keys are the option types
528 * for the elements :
529 * 'default' - default value is value
530 * 'type' - PARAM_* constant is value
531 * 'helpbutton' - helpbutton params array is value
532 * 'disabledif' - last three moodleform::disabledIf()
533 * params are value as an array
534 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
535 * @param string $addfieldsname name for button to add more fields
536 * @param int $addfieldsno how many fields to add at a time
537 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
538 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
539 * @return int no of repeats of element in this page
541 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
542 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
543 if ($addstring===null){
544 $addstring = get_string('addfields', 'form', $addfieldsno);
545 } else {
546 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
548 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
549 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
550 if (!empty($addfields)){
551 $repeats += $addfieldsno;
553 $mform =& $this->_form;
554 $mform->registerNoSubmitButton($addfieldsname);
555 $mform->addElement('hidden', $repeathiddenname, $repeats);
556 //value not to be overridden by submitted value
557 $mform->setConstants(array($repeathiddenname=>$repeats));
558 for ($i=0; $i<$repeats; $i++) {
559 foreach ($elementobjs as $elementobj){
560 $elementclone = clone($elementobj);
561 $name = $elementclone->getName();
562 if (!empty($name)){
563 $elementclone->setName($name."[$i]");
565 if (is_a($elementclone, 'HTML_QuickForm_header')){
566 $value=$elementclone->_text;
567 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
569 } else {
570 $value=$elementclone->getLabel();
571 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
575 $mform->addElement($elementclone);
578 for ($i=0; $i<$repeats; $i++) {
579 foreach ($options as $elementname => $elementoptions){
580 $pos=strpos($elementname, '[');
581 if ($pos!==FALSE){
582 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
583 $realelementname .= substr($elementname, $pos+1);
584 }else {
585 $realelementname = $elementname."[$i]";
587 foreach ($elementoptions as $option => $params){
589 switch ($option){
590 case 'default' :
591 $mform->setDefault($realelementname, $params);
592 break;
593 case 'helpbutton' :
594 $mform->setHelpButton($realelementname, $params);
595 break;
596 case 'disabledif' :
597 $params = array_merge(array($realelementname), $params);
598 call_user_func_array(array(&$mform, 'disabledIf'), $params);
599 break;
600 case 'rule' :
601 if (is_string($params)){
602 $params = array(null, $params, null, 'client');
604 $params = array_merge(array($realelementname), $params);
605 call_user_func_array(array(&$mform, 'addRule'), $params);
606 break;
612 $mform->addElement('submit', $addfieldsname, $addstring);
614 if (!$addbuttoninside) {
615 $mform->closeHeaderBefore($addfieldsname);
618 return $repeats;
621 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
622 * if you don't want a cancel button in your form. If you have a cancel button make sure you
623 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
624 * get data with get_data().
626 * @param boolean $cancel whether to show cancel button, default true
627 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
629 function add_action_buttons($cancel = true, $submitlabel=null){
630 if (is_null($submitlabel)){
631 $submitlabel = get_string('savechanges');
633 $mform =& $this->_form;
634 if ($cancel){
635 //when two elements we need a group
636 $buttonarray=array();
637 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
638 $buttonarray[] = &$mform->createElement('cancel');
639 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
640 $mform->closeHeaderBefore('buttonar');
641 } else {
642 //no group needed
643 $mform->addElement('submit', 'submitbutton', $submitlabel);
644 $mform->closeHeaderBefore('submitbutton');
650 * You never extend this class directly. The class methods of this class are available from
651 * the private $this->_form property on moodleform and it's children. You generally only
652 * call methods on this class from within abstract methods that you override on moodleform such
653 * as definition and definition_after_data
656 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
657 var $_types = array();
658 var $_dependencies = array();
660 * Array of buttons that if pressed do not result in the processing of the form.
662 * @var array
664 var $_noSubmitButtons=array();
666 * Array of buttons that if pressed do not result in the processing of the form.
668 * @var array
670 var $_cancelButtons=array();
673 * Array whose keys are element names. If the key exists this is a advanced element
675 * @var array
677 var $_advancedElements = array();
680 * Whether to display advanced elements (on page load)
682 * @var boolean
684 var $_showAdvanced = null;
687 * The form name is derrived from the class name of the wrapper minus the trailing form
688 * It is a name with words joined by underscores whereas the id attribute is words joined by
689 * underscores.
691 * @var unknown_type
693 var $_formName = '';
696 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
698 * @var string
700 var $_pageparams = '';
703 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
704 * @param string $formName Form's name.
705 * @param string $method (optional)Form's method defaults to 'POST'
706 * @param mixed $action (optional)Form's action - string or moodle_url
707 * @param string $target (optional)Form's target defaults to none
708 * @param mixed $attributes (optional)Extra attributes for <form> tag
709 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
710 * @access public
712 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
713 global $CFG;
715 static $formcounter = 1;
717 HTML_Common::HTML_Common($attributes);
718 $target = empty($target) ? array() : array('target' => $target);
719 $this->_formName = $formName;
720 if (is_a($action, 'moodle_url')){
721 $this->_pageparams = $action->hidden_params_out();
722 $action = $action->out(true);
723 } else {
724 $this->_pageparams = '';
726 //no 'name' atttribute for form in xhtml strict :
727 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
728 $formcounter++;
729 $this->updateAttributes($attributes);
731 //this is custom stuff for Moodle :
732 $oldclass= $this->getAttribute('class');
733 if (!empty($oldclass)){
734 $this->updateAttributes(array('class'=>$oldclass.' mform'));
735 }else {
736 $this->updateAttributes(array('class'=>'mform'));
738 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
739 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
740 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
741 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
745 * Use this method to indicate an element in a form is an advanced field. If items in a form
746 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
747 * form so the user can decide whether to display advanced form controls.
749 * If you set a header element to advanced then all elements it contains will also be set as advanced.
751 * @param string $elementName group or element name (not the element name of something inside a group).
752 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
754 function setAdvanced($elementName, $advanced=true){
755 if ($advanced){
756 $this->_advancedElements[$elementName]='';
757 } elseif (isset($this->_advancedElements[$elementName])) {
758 unset($this->_advancedElements[$elementName]);
760 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
761 $this->setShowAdvanced();
762 $this->registerNoSubmitButton('mform_showadvanced');
764 $this->addElement('hidden', 'mform_showadvanced_last');
768 * Set whether to show advanced elements in the form on first displaying form. Default is not to
769 * display advanced elements in the form until 'Show Advanced' is pressed.
771 * You can get the last state of the form and possibly save it for this user by using
772 * value 'mform_showadvanced_last' in submitted data.
774 * @param boolean $showadvancedNow
776 function setShowAdvanced($showadvancedNow = null){
777 if ($showadvancedNow === null){
778 if ($this->_showAdvanced !== null){
779 return;
780 } else { //if setShowAdvanced is called without any preference
781 //make the default to not show advanced elements.
782 $showadvancedNow = get_user_preferences(
783 moodle_strtolower($this->_formName.'_showadvanced', 0));
786 //value of hidden element
787 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
788 //value of button
789 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
790 //toggle if button pressed or else stay the same
791 if ($hiddenLast == -1) {
792 $next = $showadvancedNow;
793 } elseif ($buttonPressed) { //toggle on button press
794 $next = !$hiddenLast;
795 } else {
796 $next = $hiddenLast;
798 $this->_showAdvanced = $next;
799 if ($showadvancedNow != $next){
800 set_user_preference($this->_formName.'_showadvanced', $next);
802 $this->setConstants(array('mform_showadvanced_last'=>$next));
804 function getShowAdvanced(){
805 return $this->_showAdvanced;
810 * Accepts a renderer
812 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
813 * @since 3.0
814 * @access public
815 * @return void
817 function accept(&$renderer) {
818 if (method_exists($renderer, 'setAdvancedElements')){
819 //check for visible fieldsets where all elements are advanced
820 //and mark these headers as advanced as well.
821 //And mark all elements in a advanced header as advanced
822 $stopFields = $renderer->getStopFieldSetElements();
823 $lastHeader = null;
824 $lastHeaderAdvanced = false;
825 $anyAdvanced = false;
826 foreach (array_keys($this->_elements) as $elementIndex){
827 $element =& $this->_elements[$elementIndex];
829 // if closing header and any contained element was advanced then mark it as advanced
830 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
831 if ($anyAdvanced && !is_null($lastHeader)){
832 $this->setAdvanced($lastHeader->getName());
834 $lastHeaderAdvanced = false;
835 unset($lastHeader);
836 $lastHeader = null;
837 } elseif ($lastHeaderAdvanced) {
838 $this->setAdvanced($element->getName());
841 if ($element->getType()=='header'){
842 $lastHeader =& $element;
843 $anyAdvanced = false;
844 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
845 } elseif (isset($this->_advancedElements[$element->getName()])){
846 $anyAdvanced = true;
849 // the last header may not be closed yet...
850 if ($anyAdvanced && !is_null($lastHeader)){
851 $this->setAdvanced($lastHeader->getName());
853 $renderer->setAdvancedElements($this->_advancedElements);
856 parent::accept($renderer);
861 function closeHeaderBefore($elementName){
862 $renderer =& $this->defaultRenderer();
863 $renderer->addStopFieldsetElements($elementName);
867 * Should be used for all elements of a form except for select, radio and checkboxes which
868 * clean their own data.
870 * @param string $elementname
871 * @param integer $paramtype use the constants PARAM_*.
872 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
873 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
874 * It will strip all html tags. But will still let tags for multilang support
875 * through.
876 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
877 * html editor. Data from the editor is later cleaned before display using
878 * format_text() function. PARAM_RAW can also be used for data that is validated
879 * by some other way or printed by p() or s().
880 * * PARAM_INT should be used for integers.
881 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
882 * form actions.
884 function setType($elementname, $paramtype) {
885 $this->_types[$elementname] = $paramtype;
889 * See description of setType above. This can be used to set several types at once.
891 * @param array $paramtypes
893 function setTypes($paramtypes) {
894 $this->_types = $paramtypes + $this->_types;
897 function updateSubmission($submission, $files) {
898 $this->_flagSubmitted = false;
900 if (empty($submission)) {
901 $this->_submitValues = array();
902 } else {
903 foreach ($submission as $key=>$s) {
904 if (array_key_exists($key, $this->_types)) {
905 $submission[$key] = clean_param($s, $this->_types[$key]);
908 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
909 $this->_flagSubmitted = true;
912 if (empty($files)) {
913 $this->_submitFiles = array();
914 } else {
915 if (1 == get_magic_quotes_gpc()) {
916 foreach (array_keys($files) as $elname) {
917 // dangerous characters in filenames are cleaned later in upload_manager
918 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
921 $this->_submitFiles = $files;
922 $this->_flagSubmitted = true;
925 // need to tell all elements that they need to update their value attribute.
926 foreach (array_keys($this->_elements) as $key) {
927 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
931 function getReqHTML(){
932 return $this->_reqHTML;
935 function getAdvancedHTML(){
936 return $this->_advancedHTML;
940 * Initializes a default form value. Used to specify the default for a new entry where
941 * no data is loaded in using moodleform::set_data()
943 * @param string $elementname element name
944 * @param mixed $values values for that element name
945 * @param bool $slashed the default value is slashed
946 * @access public
947 * @return void
949 function setDefault($elementName, $defaultValue, $slashed=false){
950 $filter = $slashed ? 'stripslashes' : NULL;
951 $this->setDefaults(array($elementName=>$defaultValue), $filter);
952 } // end func setDefault
954 * Add an array of buttons to the form
955 * @param array $buttons An associative array representing help button to attach to
956 * to the form. keys of array correspond to names of elements in form.
958 * @access public
960 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
962 foreach ($buttons as $elementname => $button){
963 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
967 * Add a single button.
969 * @param string $elementname name of the element to add the item to
970 * @param array $button - arguments to pass to function $function
971 * @param boolean $suppresscheck - whether to throw an error if the element
972 * doesn't exist.
973 * @param string $function - function to generate html from the arguments in $button
975 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
976 if (array_key_exists($elementname, $this->_elementIndex)){
977 //_elements has a numeric index, this code accesses the elements by name
978 $element=&$this->_elements[$this->_elementIndex[$elementname]];
979 if (method_exists($element, 'setHelpButton')){
980 $element->setHelpButton($button, $function);
981 }else{
982 $a=new object();
983 $a->name=$element->getName();
984 $a->classname=get_class($element);
985 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
987 }elseif (!$suppresscheck){
988 print_error('nonexistentformelements', 'form', '', $elementname);
992 function exportValues($elementList= null, $addslashes=true){
993 $unfiltered = array();
994 if (null === $elementList) {
995 // iterate over all elements, calling their exportValue() methods
996 $emptyarray = array();
997 foreach (array_keys($this->_elements) as $key) {
998 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
999 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1000 } else {
1001 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1004 if (is_array($value)) {
1005 // This shit throws a bogus warning in PHP 4.3.x
1006 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1009 } else {
1010 if (!is_array($elementList)) {
1011 $elementList = array_map('trim', explode(',', $elementList));
1013 foreach ($elementList as $elementName) {
1014 $value = $this->exportValue($elementName);
1015 if (PEAR::isError($value)) {
1016 return $value;
1018 $unfiltered[$elementName] = $value;
1022 if ($addslashes){
1023 return $this->_recursiveFilter('addslashes', $unfiltered);
1024 } else {
1025 return $unfiltered;
1029 * Adds a validation rule for the given field
1031 * If the element is in fact a group, it will be considered as a whole.
1032 * To validate grouped elements as separated entities,
1033 * use addGroupRule instead of addRule.
1035 * @param string $element Form element name
1036 * @param string $message Message to display for invalid data
1037 * @param string $type Rule type, use getRegisteredRules() to get types
1038 * @param string $format (optional)Required for extra rule data
1039 * @param string $validation (optional)Where to perform validation: "server", "client"
1040 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1041 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1042 * @since 1.0
1043 * @access public
1044 * @throws HTML_QuickForm_Error
1046 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1048 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1049 if ($validation == 'client') {
1050 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1053 } // end func addRule
1055 * Adds a validation rule for the given group of elements
1057 * Only groups with a name can be assigned a validation rule
1058 * Use addGroupRule when you need to validate elements inside the group.
1059 * Use addRule if you need to validate the group as a whole. In this case,
1060 * the same rule will be applied to all elements in the group.
1061 * Use addRule if you need to validate the group against a function.
1063 * @param string $group Form group name
1064 * @param mixed $arg1 Array for multiple elements or error message string for one element
1065 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1066 * @param string $format (optional)Required for extra rule data
1067 * @param int $howmany (optional)How many valid elements should be in the group
1068 * @param string $validation (optional)Where to perform validation: "server", "client"
1069 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1070 * @since 2.5
1071 * @access public
1072 * @throws HTML_QuickForm_Error
1074 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1076 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1077 if (is_array($arg1)) {
1078 foreach ($arg1 as $rules) {
1079 foreach ($rules as $rule) {
1080 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1082 if ('client' == $validation) {
1083 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1087 } elseif (is_string($arg1)) {
1089 if ($validation == 'client') {
1090 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1093 } // end func addGroupRule
1095 // }}}
1097 * Returns the client side validation script
1099 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1100 * and slightly modified to run rules per-element
1101 * Needed to override this because of an error with client side validation of grouped elements.
1103 * @access public
1104 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1106 function getValidationScript()
1108 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1109 return '';
1112 include_once('HTML/QuickForm/RuleRegistry.php');
1113 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1114 $test = array();
1115 $js_escape = array(
1116 "\r" => '\r',
1117 "\n" => '\n',
1118 "\t" => '\t',
1119 "'" => "\\'",
1120 '"' => '\"',
1121 '\\' => '\\\\'
1124 foreach ($this->_rules as $elementName => $rules) {
1125 foreach ($rules as $rule) {
1126 if ('client' == $rule['validation']) {
1127 unset($element); //TODO: find out how to properly initialize it
1129 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1130 $rule['message'] = strtr($rule['message'], $js_escape);
1132 if (isset($rule['group'])) {
1133 $group =& $this->getElement($rule['group']);
1134 // No JavaScript validation for frozen elements
1135 if ($group->isFrozen()) {
1136 continue 2;
1138 $elements =& $group->getElements();
1139 foreach (array_keys($elements) as $key) {
1140 if ($elementName == $group->getElementName($key)) {
1141 $element =& $elements[$key];
1142 break;
1145 } elseif ($dependent) {
1146 $element = array();
1147 $element[] =& $this->getElement($elementName);
1148 foreach ($rule['dependent'] as $elName) {
1149 $element[] =& $this->getElement($elName);
1151 } else {
1152 $element =& $this->getElement($elementName);
1154 // No JavaScript validation for frozen elements
1155 if (is_object($element) && $element->isFrozen()) {
1156 continue 2;
1157 } elseif (is_array($element)) {
1158 foreach (array_keys($element) as $key) {
1159 if ($element[$key]->isFrozen()) {
1160 continue 3;
1164 // Fix for bug displaying errors for elements in a group
1165 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1166 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1167 $test[$elementName][1]=$element;
1168 //end of fix
1173 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1174 // the form, and then that form field gets corrupted by the code that follows.
1175 unset($element);
1177 $js = '
1178 <script type="text/javascript">
1179 //<![CDATA[
1181 var skipClientValidation = false;
1183 function qf_errorHandler(element, _qfMsg) {
1184 div = element.parentNode;
1185 if (_qfMsg != \'\') {
1186 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1187 if (!errorSpan) {
1188 errorSpan = document.createElement("span");
1189 errorSpan.id = \'id_error_\'+element.name;
1190 errorSpan.className = "error";
1191 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1194 while (errorSpan.firstChild) {
1195 errorSpan.removeChild(errorSpan.firstChild);
1198 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1199 errorSpan.appendChild(document.createElement("br"));
1201 if (div.className.substr(div.className.length - 6, 6) != " error"
1202 && div.className != "error") {
1203 div.className += " error";
1206 return false;
1207 } else {
1208 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1209 if (errorSpan) {
1210 errorSpan.parentNode.removeChild(errorSpan);
1213 if (div.className.substr(div.className.length - 6, 6) == " error") {
1214 div.className = div.className.substr(0, div.className.length - 6);
1215 } else if (div.className == "error") {
1216 div.className = "";
1219 return true;
1222 $validateJS = '';
1223 foreach ($test as $elementName => $jsandelement) {
1224 // Fix for bug displaying errors for elements in a group
1225 //unset($element);
1226 list($jsArr,$element)=$jsandelement;
1227 //end of fix
1228 $js .= '
1229 function validate_' . $this->_formName . '_' . $elementName . '(element) {
1230 var value = \'\';
1231 var errFlag = new Array();
1232 var _qfGroups = {};
1233 var _qfMsg = \'\';
1234 var frm = element.parentNode;
1235 while (frm && frm.nodeName != "FORM") {
1236 frm = frm.parentNode;
1238 ' . join("\n", $jsArr) . '
1239 return qf_errorHandler(element, _qfMsg);
1242 $validateJS .= '
1243 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1244 if (!ret && !first_focus) {
1245 first_focus = true;
1246 frm.elements[\''.$elementName.'\'].focus();
1250 // Fix for bug displaying errors for elements in a group
1251 //unset($element);
1252 //$element =& $this->getElement($elementName);
1253 //end of fix
1254 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
1255 $onBlur = $element->getAttribute('onBlur');
1256 $onChange = $element->getAttribute('onChange');
1257 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1258 'onChange' => $onChange . $valFunc));
1260 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1261 $js .= '
1262 function validate_' . $this->_formName . '(frm) {
1263 if (skipClientValidation) {
1264 return true;
1266 var ret = true;
1268 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1269 var first_focus = false;
1270 ' . $validateJS . ';
1271 return ret;
1273 //]]>
1274 </script>';
1275 return $js;
1276 } // end func getValidationScript
1277 function _setDefaultRuleMessages(){
1278 foreach ($this->_rules as $field => $rulesarr){
1279 foreach ($rulesarr as $key => $rule){
1280 if ($rule['message']===null){
1281 $a=new object();
1282 $a->format=$rule['format'];
1283 $str=get_string('err_'.$rule['type'], 'form', $a);
1284 if (strpos($str, '[[')!==0){
1285 $this->_rules[$field][$key]['message']=$str;
1292 function getLockOptionEndScript(){
1294 $iname = $this->getAttribute('id').'items';
1295 $js = '<script type="text/javascript">'."\n";
1296 $js .= '//<![CDATA['."\n";
1297 $js .= "var $iname = Array();\n";
1299 foreach ($this->_dependencies as $dependentOn => $conditions){
1300 $js .= "{$iname}['$dependentOn'] = Array();\n";
1301 foreach ($conditions as $condition=>$values) {
1302 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1303 foreach ($values as $value=>$dependents) {
1304 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1305 $i = 0;
1306 foreach ($dependents as $dependent) {
1307 $elements = $this->_getElNamesRecursive($dependent);
1308 if (empty($elements)) {
1309 // probably element inside of some group
1310 $elements = array($dependent);
1312 foreach($elements as $element) {
1313 if ($element == $dependentOn) {
1314 continue;
1316 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1317 $i++;
1323 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1324 $js .='//]]>'."\n";
1325 $js .='</script>'."\n";
1326 return $js;
1329 function _getElNamesRecursive($element) {
1330 if (is_string($element)) {
1331 if (!$this->elementExists($element)) {
1332 return array();
1334 $element = $this->getElement($element);
1337 if (is_a($element, 'HTML_QuickForm_group')) {
1338 $elsInGroup = $element->getElements();
1339 $elNames = array();
1340 foreach ($elsInGroup as $elInGroup){
1341 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1344 } else if (is_a($element, 'HTML_QuickForm_header')) {
1345 return array();
1347 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1348 return array();
1350 } else if (method_exists($element, 'getPrivateName')) {
1351 return array($element->getPrivateName());
1353 } else {
1354 $elNames = array($element->getName());
1357 return $elNames;
1361 * Adds a dependency for $elementName which will be disabled if $condition is met.
1362 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1363 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1364 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1365 * of the $dependentOn element is $condition (such as equal) to $value.
1367 * @param string $elementName the name of the element which will be disabled
1368 * @param string $dependentOn the name of the element whose state will be checked for
1369 * condition
1370 * @param string $condition the condition to check
1371 * @param mixed $value used in conjunction with condition.
1373 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1374 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1375 $this->_dependencies[$dependentOn] = array();
1377 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1378 $this->_dependencies[$dependentOn][$condition] = array();
1380 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1381 $this->_dependencies[$dependentOn][$condition][$value] = array();
1383 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1386 function registerNoSubmitButton($buttonname){
1387 $this->_noSubmitButtons[]=$buttonname;
1390 function isNoSubmitButton($buttonname){
1391 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1394 function _registerCancelButton($addfieldsname){
1395 $this->_cancelButtons[]=$addfieldsname;
1398 * Displays elements without HTML input tags.
1399 * This method is different to freeze() in that it makes sure no hidden
1400 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1401 * ignored.
1403 * This function also removes all previously defined rules.
1405 * @param mixed $elementList array or string of element(s) to be frozen
1406 * @since 1.0
1407 * @access public
1408 * @throws HTML_QuickForm_Error
1410 function hardFreeze($elementList=null)
1412 if (!isset($elementList)) {
1413 $this->_freezeAll = true;
1414 $elementList = array();
1415 } else {
1416 if (!is_array($elementList)) {
1417 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1419 $elementList = array_flip($elementList);
1422 foreach (array_keys($this->_elements) as $key) {
1423 $name = $this->_elements[$key]->getName();
1424 if ($this->_freezeAll || isset($elementList[$name])) {
1425 $this->_elements[$key]->freeze();
1426 $this->_elements[$key]->setPersistantFreeze(false);
1427 unset($elementList[$name]);
1429 // remove all rules
1430 $this->_rules[$name] = array();
1431 // if field is required, remove the rule
1432 $unset = array_search($name, $this->_required);
1433 if ($unset !== false) {
1434 unset($this->_required[$unset]);
1439 if (!empty($elementList)) {
1440 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);
1442 return true;
1445 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1447 * This function also removes all previously defined rules of elements it freezes.
1449 * @param array $elementList array or string of element(s) not to be frozen
1450 * @since 1.0
1451 * @access public
1452 * @throws HTML_QuickForm_Error
1454 function hardFreezeAllVisibleExcept($elementList)
1456 $elementList = array_flip($elementList);
1457 foreach (array_keys($this->_elements) as $key) {
1458 $name = $this->_elements[$key]->getName();
1459 $type = $this->_elements[$key]->getType();
1461 if ($type == 'hidden'){
1462 // leave hidden types as they are
1463 } elseif (!isset($elementList[$name])) {
1464 $this->_elements[$key]->freeze();
1465 $this->_elements[$key]->setPersistantFreeze(false);
1467 // remove all rules
1468 $this->_rules[$name] = array();
1469 // if field is required, remove the rule
1470 $unset = array_search($name, $this->_required);
1471 if ($unset !== false) {
1472 unset($this->_required[$unset]);
1476 return true;
1479 * Tells whether the form was already submitted
1481 * This is useful since the _submitFiles and _submitValues arrays
1482 * may be completely empty after the trackSubmit value is removed.
1484 * @access public
1485 * @return bool
1487 function isSubmitted()
1489 return parent::isSubmitted() && (!$this->isFrozen());
1495 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1496 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1498 * Stylesheet is part of standard theme and should be automatically included.
1500 * @author Jamie Pratt <me@jamiep.org>
1501 * @license gpl license
1503 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1506 * Element template array
1507 * @var array
1508 * @access private
1510 var $_elementTemplates;
1512 * Template used when opening a hidden fieldset
1513 * (i.e. a fieldset that is opened when there is no header element)
1514 * @var string
1515 * @access private
1517 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1519 * Header Template string
1520 * @var string
1521 * @access private
1523 var $_headerTemplate =
1524 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1527 * Template used when opening a fieldset
1528 * @var string
1529 * @access private
1531 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1534 * Template used when closing a fieldset
1535 * @var string
1536 * @access private
1538 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1541 * Required Note template string
1542 * @var string
1543 * @access private
1545 var $_requiredNoteTemplate =
1546 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1548 var $_advancedElements = array();
1551 * Whether to display advanced elements (on page load)
1553 * @var integer 1 means show 0 means hide
1555 var $_showAdvanced;
1557 function MoodleQuickForm_Renderer(){
1558 // switch next two lines for ol li containers for form items.
1559 // $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>');
1560 $this->_elementTemplates = array(
1561 '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>',
1563 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fgrouplabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
1565 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</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>',
1567 'nodisplay'=>'');
1569 parent::HTML_QuickForm_Renderer_Tableless();
1572 function setAdvancedElements($elements){
1573 $this->_advancedElements = $elements;
1577 * What to do when starting the form
1579 * @param MoodleQuickForm $form
1581 function startForm(&$form){
1582 $this->_reqHTML = $form->getReqHTML();
1583 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1584 $this->_advancedHTML = $form->getAdvancedHTML();
1585 $this->_showAdvanced = $form->getShowAdvanced();
1586 parent::startForm($form);
1587 if ($form->isFrozen()){
1588 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
1589 } else {
1590 $this->_hiddenHtml .= $form->_pageparams;
1596 function startGroup(&$group, $required, $error){
1597 if (method_exists($group, 'getElementTemplateType')){
1598 $html = $this->_elementTemplates[$group->getElementTemplateType()];
1599 }else{
1600 $html = $this->_elementTemplates['default'];
1603 if ($this->_showAdvanced){
1604 $advclass = ' advanced';
1605 } else {
1606 $advclass = ' advanced hide';
1608 if (isset($this->_advancedElements[$group->getName()])){
1609 $html =str_replace(' {advanced}', $advclass, $html);
1610 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1611 } else {
1612 $html =str_replace(' {advanced}', '', $html);
1613 $html =str_replace('{advancedimg}', '', $html);
1615 if (method_exists($group, 'getHelpButton')){
1616 $html =str_replace('{help}', $group->getHelpButton(), $html);
1617 }else{
1618 $html =str_replace('{help}', '', $html);
1620 $html =str_replace('{name}', $group->getName(), $html);
1621 $html =str_replace('{type}', 'fgroup', $html);
1623 $this->_templates[$group->getName()]=$html;
1624 // Fix for bug in tableless quickforms that didn't allow you to stop a
1625 // fieldset before a group of elements.
1626 // if the element name indicates the end of a fieldset, close the fieldset
1627 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1628 && $this->_fieldsetsOpen > 0
1630 $this->_html .= $this->_closeFieldsetTemplate;
1631 $this->_fieldsetsOpen--;
1633 parent::startGroup($group, $required, $error);
1636 function renderElement(&$element, $required, $error){
1637 //manipulate id of all elements before rendering
1638 if (!is_null($element->getAttribute('id'))) {
1639 $id = $element->getAttribute('id');
1640 } else {
1641 $id = $element->getName();
1643 //strip qf_ prefix and replace '[' with '_' and strip ']'
1644 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1645 if (strpos($id, 'id_') !== 0){
1646 $element->updateAttributes(array('id'=>'id_'.$id));
1649 //adding stuff to place holders in template
1650 if (method_exists($element, 'getElementTemplateType')){
1651 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1652 }else{
1653 $html = $this->_elementTemplates['default'];
1655 if ($this->_showAdvanced){
1656 $advclass = ' advanced';
1657 } else {
1658 $advclass = ' advanced hide';
1660 if (isset($this->_advancedElements[$element->getName()])){
1661 $html =str_replace(' {advanced}', $advclass, $html);
1662 } else {
1663 $html =str_replace(' {advanced}', '', $html);
1665 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1666 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1667 } else {
1668 $html =str_replace('{advancedimg}', '', $html);
1670 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1671 $html =str_replace('{name}', $element->getName(), $html);
1672 if (method_exists($element, 'getHelpButton')){
1673 $html = str_replace('{help}', $element->getHelpButton(), $html);
1674 }else{
1675 $html = str_replace('{help}', '', $html);
1678 if (!isset($this->_templates[$element->getName()])) {
1679 $this->_templates[$element->getName()] = $html;
1682 parent::renderElement($element, $required, $error);
1685 function finishForm(&$form){
1686 if ($form->isFrozen()){
1687 $this->_hiddenHtml = '';
1689 parent::finishForm($form);
1690 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1691 // add a lockoptions script
1692 $this->_html = $this->_html . "\n" . $script;
1696 * Called when visiting a header element
1698 * @param object An HTML_QuickForm_header element being visited
1699 * @access public
1700 * @return void
1702 function renderHeader(&$header) {
1703 $name = $header->getName();
1705 $id = empty($name) ? '' : ' id="' . $name . '"';
1706 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1707 if (is_null($header->_text)) {
1708 $header_html = '';
1709 } elseif (!empty($name) && isset($this->_templates[$name])) {
1710 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1711 } else {
1712 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1715 if (isset($this->_advancedElements[$name])){
1716 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1717 } else {
1718 $header_html =str_replace('{advancedimg}', '', $header_html);
1720 $elementName='mform_showadvanced';
1721 if ($this->_showAdvanced==0){
1722 $buttonlabel = get_string('showadvanced', 'form');
1723 } else {
1724 $buttonlabel = get_string('hideadvanced', 'form');
1727 if (isset($this->_advancedElements[$name])){
1728 // this is tricky - the first submit button on form is "clicked" if user presses enter
1729 // we do not want to "submit" using advanced button if javascript active
1730 $showtext="'".get_string('showadvanced', 'form')."'";
1731 $hidetext="'".get_string('hideadvanced', 'form')."'";
1732 //onclick returns false so if js is on then page is not submitted.
1733 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1734 $button_js = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="button" onclick="'.$onclick.'" />';
1735 $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />';
1736 $button = '<script type="text/javascript">
1737 //<![CDATA[
1738 document.write("'.addslashes_js($button_js).'")
1739 //]]>
1740 </script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation
1742 $header_html = str_replace('{button}', $button, $header_html);
1743 } else {
1744 $header_html = str_replace('{button}', '', $header_html);
1747 if ($this->_fieldsetsOpen > 0) {
1748 $this->_html .= $this->_closeFieldsetTemplate;
1749 $this->_fieldsetsOpen--;
1752 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1753 if ($this->_showAdvanced){
1754 $advclass = ' class="advanced"';
1755 } else {
1756 $advclass = ' class="advanced hide"';
1758 if (isset($this->_advancedElements[$name])){
1759 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1760 } else {
1761 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1763 $this->_html .= $openFieldsetTemplate . $header_html;
1764 $this->_fieldsetsOpen++;
1765 } // end func renderHeader
1767 function getStopFieldsetElements(){
1768 return $this->_stopFieldsetElements;
1773 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1775 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1776 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1777 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1778 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1779 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1780 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1781 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1782 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1783 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1784 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1785 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1786 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1787 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1788 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1789 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1790 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1791 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1792 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1793 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1794 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1795 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1796 MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1797 MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1798 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1799 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1800 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1801 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');