MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / lib / formslib.php
blobb12392b03abe31acd9f58f483587835bcacc9e6f
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 if (isset($form->_errors) && 0 != count($form->_errors)){
145 $errorkeys = array_keys($form->_errors);
146 $elkeys = array_intersect($elkeys, $errorkeys);
148 $names=null;
149 while (!$names){
150 $el = array_shift($elkeys);
151 $names = $form->_getElNamesRecursive($el);
153 if (empty($name)) {
154 $name=array_shift($names);
156 $focus='forms[\''.$this->_form->getAttribute('id').'\'].elements[\''.$name.'\']';
157 return $focus;
161 * Internal method. Alters submitted data to be suitable for quickforms processing.
162 * Must be called when the form is fully set up.
164 function _process_submission($method) {
165 $submission = array();
166 if ($method == 'post') {
167 if (!empty($_POST)) {
168 $submission = $_POST;
170 } else {
171 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
174 // following trick is needed to enable proper sesskey checks when using GET forms
175 // the _qf__.$this->_formname serves as a marker that form was actually submitted
176 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
177 if (!confirm_sesskey()) {
178 error('Incorrect sesskey submitted, form not accepted!');
180 $files = $_FILES;
181 } else {
182 $submission = array();
183 $files = array();
186 $this->_form->updateSubmission($submission, $files);
190 * Internal method. Validates all uploaded files.
192 function _validate_files(&$files) {
193 $files = array();
195 if (empty($_FILES)) {
196 // we do not need to do any checks because no files were submitted
197 // note: server side rules do not work for files - use custom verification in validate() instead
198 return true;
200 $errors = array();
201 $mform =& $this->_form;
203 // check the files
204 $status = $this->_upload_manager->preprocess_files();
206 // now check that we really want each file
207 foreach ($_FILES as $elname=>$file) {
208 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
209 $required = $mform->isElementRequired($elname);
210 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
211 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
212 // file not uploaded and not required - ignore it
213 continue;
215 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
217 } else if ($this->_upload_manager->files[$elname]['clear']) {
218 $files[$elname] = $this->_upload_manager->files[$elname]['tmp_name'];
220 } else {
221 error('Incorrect upload attempt!');
225 // return errors if found
226 if ($status and 0 == count($errors)){
227 return true;
229 } else {
230 $files = array();
231 return $errors;
236 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
237 * form definition (new entry form); this function is used to load in data where values
238 * already exist and data is being edited (edit entry form).
240 * @param mixed $default_values object or array of default values
241 * @param bool $slased true if magic quotes applied to data values
243 function set_data($default_values, $slashed=false) {
244 if (is_object($default_values)) {
245 $default_values = (array)$default_values;
247 $filter = $slashed ? 'stripslashes' : NULL;
248 $this->_form->setDefaults($default_values, $filter);
252 * Set custom upload manager.
253 * Must be used BEFORE creating of file element!
255 * @param object $um - custom upload manager
257 function set_upload_manager($um=false) {
258 if ($um === false) {
259 $um = new upload_manager();
261 $this->_upload_manager = $um;
263 $this->_form->setMaxFileSize($um->config->maxbytes);
267 * Check that form was submitted. Does not check validity of submitted data.
269 * @return bool true if form properly submitted
271 function is_submitted() {
272 return $this->_form->isSubmitted();
275 function no_submit_button_pressed(){
276 static $nosubmit = null; // one check is enough
277 if (!is_null($nosubmit)){
278 return $nosubmit;
280 $mform =& $this->_form;
281 $nosubmit = false;
282 if (!$this->is_submitted()){
283 return false;
285 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
286 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
287 $nosubmit = true;
288 break;
291 return $nosubmit;
296 * Check that form data is valid.
298 * @return bool true if form data valid
300 function is_validated() {
301 static $validated = null; // one validation is enough
302 $mform =& $this->_form;
304 //finalize the form definition before any processing
305 if (!$this->_definition_finalized) {
306 $this->_definition_finalized = true;
307 $this->definition_after_data();
310 if ($this->no_submit_button_pressed()){
311 return false;
312 } elseif ($validated === null) {
313 $internal_val = $mform->validate();
315 $files = array();
316 $file_val = $this->_validate_files($files);
317 if ($file_val !== true) {
318 if (!empty($file_val)) {
319 foreach ($file_val as $element=>$msg) {
320 $mform->setElementError($element, $msg);
323 $file_val = false;
326 $data = $mform->exportValues(null, true);
327 $moodle_val = $this->validation($data, $files);
328 if ($moodle_val !== true) {
329 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
330 foreach ($moodle_val as $element=>$msg) {
331 $mform->setElementError($element, $msg);
333 $moodle_val = false;
334 } else {
335 $moodle_val = true;
339 $validated = ($internal_val and $moodle_val and $file_val);
341 return $validated;
345 * Return true if a cancel button has been pressed resulting in the form being submitted.
347 * @return boolean true if a cancel button has been pressed
349 function is_cancelled(){
350 $mform =& $this->_form;
351 if ($mform->isSubmitted()){
352 foreach ($mform->_cancelButtons as $cancelbutton){
353 if (optional_param($cancelbutton, 0, PARAM_RAW)){
354 return true;
358 return false;
362 * Return submitted data if properly submitted or returns NULL if validation fails or
363 * if there is no submitted data.
365 * @param bool $slashed true means return data with addslashes applied
366 * @return object submitted data; NULL if not valid or not submitted
368 function get_data($slashed=true) {
369 $mform =& $this->_form;
371 if ($this->is_submitted() and $this->is_validated()) {
372 $data = $mform->exportValues(null, $slashed);
373 unset($data['sesskey']); // we do not need to return sesskey
374 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
375 if (empty($data)) {
376 return NULL;
377 } else {
378 return (object)$data;
380 } else {
381 return NULL;
386 * Return submitted data without validation or NULL if there is no submitted data.
388 * @param bool $slashed true means return data with addslashes applied
389 * @return object submitted data; NULL if not submitted
391 function get_submitted_data($slashed=true) {
392 $mform =& $this->_form;
394 if ($this->is_submitted()) {
395 $data = $mform->exportValues(null, $slashed);
396 unset($data['sesskey']); // we do not need to return sesskey
397 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
398 if (empty($data)) {
399 return NULL;
400 } else {
401 return (object)$data;
403 } else {
404 return NULL;
409 * Save verified uploaded files into directory. Upload process can be customised from definition()
410 * method by creating instance of upload manager and storing it in $this->_upload_form
412 * @param string $destination where to store uploaded files
413 * @return bool success
415 function save_files($destination) {
416 if ($this->is_submitted() and $this->is_validated()) {
417 return $this->_upload_manager->save_files($destination);
419 return false;
423 * If we're only handling one file (if inputname was given in the constructor)
424 * this will return the (possibly changed) filename of the file.
425 * @return mixed false in case of failure, string if ok
427 function get_new_filename() {
428 return $this->_upload_manager->get_new_filename();
432 * Get content of uploaded file.
433 * @param $element name of file upload element
434 * @return mixed false in case of failure, string if ok
436 function get_file_content($elname) {
437 if (!$this->is_submitted() or !$this->is_validated()) {
438 return false;
441 if (!$this->_form->elementExists($elname)) {
442 return false;
445 if (empty($this->_upload_manager->files[$elname]['clear'])) {
446 return false;
449 if (empty($this->_upload_manager->files[$elname]['tmp_name'])) {
450 return false;
453 $data = "";
454 $file = @fopen($this->_upload_manager->files[$elname]['tmp_name'], "rb");
455 if ($file) {
456 while (!feof($file)) {
457 $data .= fread($file, 1024); // TODO: do we really have to do this?
459 fclose($file);
460 return $data;
461 } else {
462 return false;
467 * Print html form.
469 function display() {
470 //finalize the form definition if not yet done
471 if (!$this->_definition_finalized) {
472 $this->_definition_finalized = true;
473 $this->definition_after_data();
475 $this->_form->display();
479 * Abstract method - always override!
481 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
483 function definition() {
484 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
488 * Dummy stub method - override if you need to setup the form depending on current
489 * values. This method is called after definition(), data submission and set_data().
490 * All form setup that is dependent on form values should go in here.
492 function definition_after_data(){
496 * Dummy stub method - override if you needed to perform some extra validation.
497 * If there are errors return array of errors ("fieldname"=>"error message"),
498 * otherwise true if ok.
500 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
502 * @param array $data array of ("fieldname"=>value) of submitted data
503 * @param array $files array of uploaded files "element_name"=>tmp_file_path
504 * @return bool array of errors or true if ok "element_name"=>"error_description"
506 function validation($data, $files) {
507 return true;
511 * Method to add a repeating group of elements to a form.
513 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
514 * @param integer $repeats no of times to repeat elements initially
515 * @param array $options Array of options to apply to elements. Array keys are element names.
516 * This is an array of arrays. The second sets of keys are the option types
517 * for the elements :
518 * 'default' - default value is value
519 * 'type' - PARAM_* constant is value
520 * 'helpbutton' - helpbutton params array is value
521 * 'disabledif' - last three moodleform::disabledIf()
522 * params are value as an array
523 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
524 * @param string $addfieldsname name for button to add more fields
525 * @param int $addfieldsno how many fields to add at a time
526 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
527 * @return int no of repeats of element in this page
529 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, $addfieldsname, $addfieldsno=5, $addstring=null){
530 if ($addstring===null){
531 $addstring = get_string('addfields', 'form', $addfieldsno);
532 } else {
533 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
535 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
536 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
537 if (!empty($addfields)){
538 $repeats += $addfieldsno;
540 $mform =& $this->_form;
541 $mform->registerNoSubmitButton($addfieldsname);
542 $mform->addElement('hidden', $repeathiddenname, $repeats);
543 //value not to be overridden by submitted value
544 $mform->setConstants(array($repeathiddenname=>$repeats));
545 for ($i=0; $i<$repeats; $i++) {
546 foreach ($elementobjs as $elementobj){
547 $elementclone = clone($elementobj);
548 $name = $elementclone->getName();
549 if (!empty($name)){
550 $elementclone->setName($name."[$i]");
552 if (is_a($elementclone, 'HTML_QuickForm_header')){
553 $value=$elementclone->_text;
554 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
556 } else {
557 $value=$elementclone->getLabel();
558 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
562 $mform->addElement($elementclone);
565 for ($i=0; $i<$repeats; $i++) {
566 foreach ($options as $elementname => $elementoptions){
567 $pos=strpos($elementname, '[');
568 if ($pos!==FALSE){
569 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
570 $realelementname .= substr($elementname, $pos+1);
571 }else {
572 $realelementname = $elementname."[$i]";
574 foreach ($elementoptions as $option => $params){
576 switch ($option){
577 case 'default' :
578 $mform->setDefault($realelementname, $params);
579 break;
580 case 'helpbutton' :
581 $mform->setHelpButton($realelementname, $params);
582 break;
583 case 'disabledif' :
584 $params = array_merge(array($realelementname), $params);
585 call_user_func_array(array(&$mform, 'disabledIf'), $params);
586 break;
587 case 'rule' :
588 if (is_string($params)){
589 $params = array(null, $params, null, 'client');
591 $params = array_merge(array($realelementname), $params);
592 call_user_func_array(array(&$mform, 'addRule'), $params);
593 break;
599 $mform->addElement('submit', $addfieldsname, $addstring);
601 $mform->closeHeaderBefore($addfieldsname);
603 return $repeats;
606 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
607 * if you don't want a cancel button in your form. If you have a cancel button make sure you
608 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
609 * get data with get_data().
611 * @param boolean $cancel whether to show cancel button, default true
612 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
614 function add_action_buttons($cancel = true, $submitlabel=null){
615 if (is_null($submitlabel)){
616 $submitlabel = get_string('savechanges');
618 $mform =& $this->_form;
619 if ($cancel){
620 //when two elements we need a group
621 $buttonarray=array();
622 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
623 $buttonarray[] = &$mform->createElement('cancel');
624 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
625 $mform->closeHeaderBefore('buttonar');
626 } else {
627 //no group needed
628 $mform->addElement('submit', 'submitbutton', $submitlabel);
629 $mform->closeHeaderBefore('submitbutton');
635 * You never extend this class directly. The class methods of this class are available from
636 * the private $this->_form property on moodleform and it's children. You generally only
637 * call methods on this class from within abstract methods that you override on moodleform such
638 * as definition and definition_after_data
641 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
642 var $_types = array();
643 var $_dependencies = array();
645 * Array of buttons that if pressed do not result in the processing of the form.
647 * @var array
649 var $_noSubmitButtons=array();
651 * Array of buttons that if pressed do not result in the processing of the form.
653 * @var array
655 var $_cancelButtons=array();
658 * Array whose keys are element names. If the key exists this is a advanced element
660 * @var array
662 var $_advancedElements = array();
665 * Whether to display advanced elements (on page load)
667 * @var boolean
669 var $_showAdvanced = null;
672 * The form name is derrived from the class name of the wrapper minus the trailing form
673 * It is a name with words joined by underscores whereas the id attribute is words joined by
674 * underscores.
676 * @var unknown_type
678 var $_formName = '';
681 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
683 * @var string
685 var $_pageparams = '';
688 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
689 * @param string $formName Form's name.
690 * @param string $method (optional)Form's method defaults to 'POST'
691 * @param mixed $action (optional)Form's action - string or moodle_url
692 * @param string $target (optional)Form's target defaults to none
693 * @param mixed $attributes (optional)Extra attributes for <form> tag
694 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
695 * @access public
697 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
698 global $CFG;
700 static $formcounter = 1;
702 HTML_Common::HTML_Common($attributes);
703 $target = empty($target) ? array() : array('target' => $target);
704 $this->_formName = $formName;
705 if (is_a($action, 'moodle_url')){
706 $this->_pageparams = $action->hidden_params_out();
707 $action = $action->out(true);
708 } else {
709 $this->_pageparams = '';
711 //no 'name' atttribute for form in xhtml strict :
712 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
713 $formcounter++;
714 $this->updateAttributes($attributes);
716 //this is custom stuff for Moodle :
717 $oldclass= $this->getAttribute('class');
718 if (!empty($oldclass)){
719 $this->updateAttributes(array('class'=>$oldclass.' mform'));
720 }else {
721 $this->updateAttributes(array('class'=>'mform'));
723 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
724 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
725 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
726 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
730 * Use this method to indicate an element in a form is an advanced field. If items in a form
731 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
732 * form so the user can decide whether to display advanced form controls.
734 * If you set a header element to advanced then all elements it contains will also be set as advanced.
736 * @param string $elementName group or element name (not the element name of something inside a group).
737 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
739 function setAdvanced($elementName, $advanced=true){
740 if ($advanced){
741 $this->_advancedElements[$elementName]='';
742 } elseif (isset($this->_advancedElements[$elementName])) {
743 unset($this->_advancedElements[$elementName]);
745 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
746 $this->setShowAdvanced();
747 $this->registerNoSubmitButton('mform_showadvanced');
749 $this->addElement('hidden', 'mform_showadvanced_last');
753 * Set whether to show advanced elements in the form on first displaying form. Default is not to
754 * display advanced elements in the form until 'Show Advanced' is pressed.
756 * You can get the last state of the form and possibly save it for this user by using
757 * value 'mform_showadvanced_last' in submitted data.
759 * @param boolean $showadvancedNow
761 function setShowAdvanced($showadvancedNow = null){
762 if ($showadvancedNow === null){
763 if ($this->_showAdvanced !== null){
764 return;
765 } else { //if setShowAdvanced is called without any preference
766 //make the default to not show advanced elements.
767 $showadvancedNow = get_user_preferences(
768 moodle_strtolower($this->_formName.'_showadvanced', 0));
771 //value of hidden element
772 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
773 //value of button
774 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
775 //toggle if button pressed or else stay the same
776 if ($hiddenLast == -1) {
777 $next = $showadvancedNow;
778 } elseif ($buttonPressed) { //toggle on button press
779 $next = !$hiddenLast;
780 } else {
781 $next = $hiddenLast;
783 $this->_showAdvanced = $next;
784 if ($showadvancedNow != $next){
785 set_user_preference($this->_formName.'_showadvanced', $next);
787 $this->setConstants(array('mform_showadvanced_last'=>$next));
789 function getShowAdvanced(){
790 return $this->_showAdvanced;
795 * Accepts a renderer
797 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
798 * @since 3.0
799 * @access public
800 * @return void
802 function accept(&$renderer)
804 if (method_exists($renderer, 'setAdvancedElements')){
805 //check for visible fieldsets where all elements are advanced
806 //and mark these headers as advanced as well.
807 //And mark all elements in a advanced header as advanced
808 $stopFields = $renderer->getStopFieldSetElements();
809 $lastHeader = null;
810 $lastHeaderAdvanced = false;
811 $anyAdvanced = false;
812 foreach (array_keys($this->_elements) as $elementIndex){
813 $element =& $this->_elements[$elementIndex];
814 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
815 if ($anyAdvanced && ($lastHeader!==null)){
816 $this->setAdvanced($lastHeader->getName());
818 $lastHeaderAdvanced = false;
819 } elseif ($lastHeaderAdvanced) {
820 $this->setAdvanced($element->getName());
822 if ($element->getType()=='header'){
823 $lastHeader =& $element;
824 $anyAdvanced = false;
825 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
826 } elseif (isset($this->_advancedElements[$element->getName()])){
827 $anyAdvanced = true;
830 $renderer->setAdvancedElements($this->_advancedElements);
833 parent::accept($renderer);
838 function closeHeaderBefore($elementName){
839 $renderer =& $this->defaultRenderer();
840 $renderer->addStopFieldsetElements($elementName);
844 * Should be used for all elements of a form except for select, radio and checkboxes which
845 * clean their own data.
847 * @param string $elementname
848 * @param integer $paramtype use the constants PARAM_*.
849 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
850 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
851 * It will strip all html tags. But will still let tags for multilang support
852 * through.
853 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
854 * html editor. Data from the editor is later cleaned before display using
855 * format_text() function. PARAM_RAW can also be used for data that is validated
856 * by some other way or printed by p() or s().
857 * * PARAM_INT should be used for integers.
858 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
859 * form actions.
861 function setType($elementname, $paramtype) {
862 $this->_types[$elementname] = $paramtype;
866 * See description of setType above. This can be used to set several types at once.
868 * @param array $paramtypes
870 function setTypes($paramtypes) {
871 $this->_types = $paramtypes + $this->_types;
874 function updateSubmission($submission, $files) {
875 $this->_flagSubmitted = false;
877 if (empty($submission)) {
878 $this->_submitValues = array();
879 } else {
880 foreach ($submission as $key=>$s) {
881 if (array_key_exists($key, $this->_types)) {
882 $submission[$key] = clean_param($s, $this->_types[$key]);
885 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
886 $this->_flagSubmitted = true;
889 if (empty($files)) {
890 $this->_submitFiles = array();
891 } else {
892 if (1 == get_magic_quotes_gpc()) {
893 foreach (array_keys($files) as $elname) {
894 // dangerous characters in filenames are cleaned later in upload_manager
895 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
898 $this->_submitFiles = $files;
899 $this->_flagSubmitted = true;
902 // need to tell all elements that they need to update their value attribute.
903 foreach (array_keys($this->_elements) as $key) {
904 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
908 function getReqHTML(){
909 return $this->_reqHTML;
912 function getAdvancedHTML(){
913 return $this->_advancedHTML;
917 * Initializes a default form value. Used to specify the default for a new entry where
918 * no data is loaded in using moodleform::set_data()
920 * @param string $elementname element name
921 * @param mixed $values values for that element name
922 * @param bool $slashed the default value is slashed
923 * @access public
924 * @return void
926 function setDefault($elementName, $defaultValue, $slashed=false){
927 $filter = $slashed ? 'stripslashes' : NULL;
928 $this->setDefaults(array($elementName=>$defaultValue), $filter);
929 } // end func setDefault
931 * Add an array of buttons to the form
932 * @param array $buttons An associative array representing help button to attach to
933 * to the form. keys of array correspond to names of elements in form.
935 * @access public
937 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
939 foreach ($buttons as $elementname => $button){
940 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
944 * Add a single button.
946 * @param string $elementname name of the element to add the item to
947 * @param array $button - arguments to pass to function $function
948 * @param boolean $suppresscheck - whether to throw an error if the element
949 * doesn't exist.
950 * @param string $function - function to generate html from the arguments in $button
952 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
953 if (array_key_exists($elementname, $this->_elementIndex)){
954 //_elements has a numeric index, this code accesses the elements by name
955 $element=&$this->_elements[$this->_elementIndex[$elementname]];
956 if (method_exists($element, 'setHelpButton')){
957 $element->setHelpButton($button, $function);
958 }else{
959 $a=new object();
960 $a->name=$element->getName();
961 $a->classname=get_class($element);
962 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
964 }elseif (!$suppresscheck){
965 print_error('nonexistentformelements', 'form', '', $elementname);
969 function exportValues($elementList= null, $addslashes=true){
970 $unfiltered = array();
971 if (null === $elementList) {
972 // iterate over all elements, calling their exportValue() methods
973 $emptyarray = array();
974 foreach (array_keys($this->_elements) as $key) {
975 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
976 $value = $this->_elements[$key]->exportValue($emptyarray, true);
977 } else {
978 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
981 if (is_array($value)) {
982 // This shit throws a bogus warning in PHP 4.3.x
983 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
986 } else {
987 if (!is_array($elementList)) {
988 $elementList = array_map('trim', explode(',', $elementList));
990 foreach ($elementList as $elementName) {
991 $value = $this->exportValue($elementName);
992 if (PEAR::isError($value)) {
993 return $value;
995 $unfiltered[$elementName] = $value;
999 if ($addslashes){
1000 return $this->_recursiveFilter('addslashes', $unfiltered);
1001 } else {
1002 return $unfiltered;
1006 * Adds a validation rule for the given field
1008 * If the element is in fact a group, it will be considered as a whole.
1009 * To validate grouped elements as separated entities,
1010 * use addGroupRule instead of addRule.
1012 * @param string $element Form element name
1013 * @param string $message Message to display for invalid data
1014 * @param string $type Rule type, use getRegisteredRules() to get types
1015 * @param string $format (optional)Required for extra rule data
1016 * @param string $validation (optional)Where to perform validation: "server", "client"
1017 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1018 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1019 * @since 1.0
1020 * @access public
1021 * @throws HTML_QuickForm_Error
1023 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1025 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1026 if ($validation == 'client') {
1027 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1030 } // end func addRule
1032 * Adds a validation rule for the given group of elements
1034 * Only groups with a name can be assigned a validation rule
1035 * Use addGroupRule when you need to validate elements inside the group.
1036 * Use addRule if you need to validate the group as a whole. In this case,
1037 * the same rule will be applied to all elements in the group.
1038 * Use addRule if you need to validate the group against a function.
1040 * @param string $group Form group name
1041 * @param mixed $arg1 Array for multiple elements or error message string for one element
1042 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1043 * @param string $format (optional)Required for extra rule data
1044 * @param int $howmany (optional)How many valid elements should be in the group
1045 * @param string $validation (optional)Where to perform validation: "server", "client"
1046 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1047 * @since 2.5
1048 * @access public
1049 * @throws HTML_QuickForm_Error
1051 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1053 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1054 if (is_array($arg1)) {
1055 foreach ($arg1 as $rules) {
1056 foreach ($rules as $rule) {
1057 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1059 if ('client' == $validation) {
1060 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1064 } elseif (is_string($arg1)) {
1066 if ($validation == 'client') {
1067 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1070 } // end func addGroupRule
1072 // }}}
1074 * Returns the client side validation script
1076 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1077 * and slightly modified to run rules per-element
1078 * Needed to override this because of an error with client side validation of grouped elements.
1080 * @access public
1081 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1083 function getValidationScript()
1085 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1086 return '';
1089 include_once('HTML/QuickForm/RuleRegistry.php');
1090 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1091 $test = array();
1092 $js_escape = array(
1093 "\r" => '\r',
1094 "\n" => '\n',
1095 "\t" => '\t',
1096 "'" => "\\'",
1097 '"' => '\"',
1098 '\\' => '\\\\'
1101 foreach ($this->_rules as $elementName => $rules) {
1102 foreach ($rules as $rule) {
1103 if ('client' == $rule['validation']) {
1104 unset($element); //TODO: find out how to properly initialize it
1106 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1107 $rule['message'] = strtr($rule['message'], $js_escape);
1109 if (isset($rule['group'])) {
1110 $group =& $this->getElement($rule['group']);
1111 // No JavaScript validation for frozen elements
1112 if ($group->isFrozen()) {
1113 continue 2;
1115 $elements =& $group->getElements();
1116 foreach (array_keys($elements) as $key) {
1117 if ($elementName == $group->getElementName($key)) {
1118 $element =& $elements[$key];
1119 break;
1122 } elseif ($dependent) {
1123 $element = array();
1124 $element[] =& $this->getElement($elementName);
1125 foreach ($rule['dependent'] as $elName) {
1126 $element[] =& $this->getElement($elName);
1128 } else {
1129 $element =& $this->getElement($elementName);
1131 // No JavaScript validation for frozen elements
1132 if (is_object($element) && $element->isFrozen()) {
1133 continue 2;
1134 } elseif (is_array($element)) {
1135 foreach (array_keys($element) as $key) {
1136 if ($element[$key]->isFrozen()) {
1137 continue 3;
1141 // Fix for bug displaying errors for elements in a group
1142 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1143 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1144 $test[$elementName][1]=$element;
1145 //end of fix
1150 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1151 // the form, and then that form field gets corrupted by the code that follows.
1152 unset($element);
1154 $js = '
1155 <script type="text/javascript">
1156 //<![CDATA[
1158 var skipClientValidation = false;
1160 function qf_errorHandler(element, _qfMsg) {
1161 div = element.parentNode;
1162 if (_qfMsg != \'\') {
1163 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1164 if (!errorSpan) {
1165 errorSpan = document.createElement("span");
1166 errorSpan.id = \'id_error_\'+element.name;
1167 errorSpan.className = "error";
1168 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1171 while (errorSpan.firstChild) {
1172 errorSpan.removeChild(errorSpan.firstChild);
1175 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1176 errorSpan.appendChild(document.createElement("br"));
1178 if (div.className.substr(div.className.length - 6, 6) != " error"
1179 && div.className != "error") {
1180 div.className += " error";
1183 return false;
1184 } else {
1185 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1186 if (errorSpan) {
1187 errorSpan.parentNode.removeChild(errorSpan);
1190 if (div.className.substr(div.className.length - 6, 6) == " error") {
1191 div.className = div.className.substr(0, div.className.length - 6);
1192 } else if (div.className == "error") {
1193 div.className = "";
1196 return true;
1199 $validateJS = '';
1200 foreach ($test as $elementName => $jsandelement) {
1201 // Fix for bug displaying errors for elements in a group
1202 //unset($element);
1203 list($jsArr,$element)=$jsandelement;
1204 //end of fix
1205 $js .= '
1206 function validate_' . $this->_formName . '_' . $elementName . '(element) {
1207 var value = \'\';
1208 var errFlag = new Array();
1209 var _qfGroups = {};
1210 var _qfMsg = \'\';
1211 var frm = element.parentNode;
1212 while (frm && frm.nodeName != "FORM") {
1213 frm = frm.parentNode;
1215 ' . join("\n", $jsArr) . '
1216 return qf_errorHandler(element, _qfMsg);
1219 $validateJS .= '
1220 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1221 if (!ret && !first_focus) {
1222 first_focus = true;
1223 frm.elements[\''.$elementName.'\'].focus();
1227 // Fix for bug displaying errors for elements in a group
1228 //unset($element);
1229 //$element =& $this->getElement($elementName);
1230 //end of fix
1231 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
1232 $onBlur = $element->getAttribute('onBlur');
1233 $onChange = $element->getAttribute('onChange');
1234 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1235 'onChange' => $onChange . $valFunc));
1237 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1238 $js .= '
1239 function validate_' . $this->_formName . '(frm) {
1240 if (skipClientValidation) {
1241 return true;
1243 var ret = true;
1245 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1246 var first_focus = false;
1247 ' . $validateJS . ';
1248 return ret;
1250 //]]>
1251 </script>';
1252 return $js;
1253 } // end func getValidationScript
1254 function _setDefaultRuleMessages(){
1255 foreach ($this->_rules as $field => $rulesarr){
1256 foreach ($rulesarr as $key => $rule){
1257 if ($rule['message']===null){
1258 $a=new object();
1259 $a->format=$rule['format'];
1260 $str=get_string('err_'.$rule['type'], 'form', $a);
1261 if (strpos($str, '[[')!==0){
1262 $this->_rules[$field][$key]['message']=$str;
1269 function getLockOptionEndScript(){
1271 $iname = $this->getAttribute('id').'items';
1272 $js = '<script type="text/javascript">'."\n";
1273 $js .= '//<![CDATA['."\n";
1274 $js .= "var $iname = Array();\n";
1276 foreach ($this->_dependencies as $dependentOn => $conditions){
1277 $js .= "{$iname}['$dependentOn'] = Array();\n";
1278 foreach ($conditions as $condition=>$values) {
1279 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1280 foreach ($values as $value=>$dependents) {
1281 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1282 $i = 0;
1283 foreach ($dependents as $dependent) {
1284 $elements = $this->_getElNamesRecursive($dependent);
1285 foreach($elements as $element) {
1286 if ($element == $dependentOn) {
1287 continue;
1289 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1290 $i++;
1296 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1297 $js .='//]]>'."\n";
1298 $js .='</script>'."\n";
1299 return $js;
1302 function _getElNamesRecursive($element, $group=null){
1303 if ($group==null){
1304 if (!$this->elementExists($element)) {
1305 return array();
1307 $el = $this->getElement($element);
1308 } else {
1309 $el = &$element;
1311 if (is_a($el, 'HTML_QuickForm_group')){
1312 $group = $el;
1313 $elsInGroup = $group->getElements();
1314 $elNames = array();
1315 foreach ($elsInGroup as $elInGroup){
1316 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1318 }else{
1319 if ($group != null){
1320 $elNames = array($group->getElementName($el->getName()));
1321 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1322 return null;
1323 } elseif (is_a($el, 'HTML_QuickForm_hidden')) {
1324 return null;
1325 } elseif (method_exists($el, 'getPrivateName')) {
1326 return array($el->getPrivateName());
1327 } else {
1328 $elNames = array($el->getName());
1331 return $elNames;
1335 * Adds a dependency for $elementName which will be disabled if $condition is met.
1336 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1337 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1338 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1339 * of the $dependentOn element is $condition (such as equal) to $value.
1341 * @param string $elementName the name of the element which will be disabled
1342 * @param string $dependentOn the name of the element whose state will be checked for
1343 * condition
1344 * @param string $condition the condition to check
1345 * @param mixed $value used in conjunction with condition.
1347 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1348 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1349 $this->_dependencies[$dependentOn] = array();
1351 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1352 $this->_dependencies[$dependentOn][$condition] = array();
1354 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1355 $this->_dependencies[$dependentOn][$condition][$value] = array();
1357 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1360 function registerNoSubmitButton($buttonname){
1361 $this->_noSubmitButtons[]=$buttonname;
1364 function isNoSubmitButton($buttonname){
1365 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1368 function _registerCancelButton($addfieldsname){
1369 $this->_cancelButtons[]=$addfieldsname;
1372 * Displays elements without HTML input tags.
1373 * This method is different to freeze() in that it makes sure no hidden
1374 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1375 * ignored.
1377 * This function also removes all previously defined rules.
1379 * @param mixed $elementList array or string of element(s) to be frozen
1380 * @since 1.0
1381 * @access public
1382 * @throws HTML_QuickForm_Error
1384 function hardFreeze($elementList=null)
1386 if (!isset($elementList)) {
1387 $this->_freezeAll = true;
1388 $elementList = array();
1389 } else {
1390 if (!is_array($elementList)) {
1391 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1393 $elementList = array_flip($elementList);
1396 foreach (array_keys($this->_elements) as $key) {
1397 $name = $this->_elements[$key]->getName();
1398 if ($this->_freezeAll || isset($elementList[$name])) {
1399 $this->_elements[$key]->freeze();
1400 $this->_elements[$key]->setPersistantFreeze(false);
1401 unset($elementList[$name]);
1403 // remove all rules
1404 $this->_rules[$name] = array();
1405 // if field is required, remove the rule
1406 $unset = array_search($name, $this->_required);
1407 if ($unset !== false) {
1408 unset($this->_required[$unset]);
1413 if (!empty($elementList)) {
1414 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);
1416 return true;
1419 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1421 * This function also removes all previously defined rules of elements it freezes.
1423 * @param array $elementList array or string of element(s) not to be frozen
1424 * @since 1.0
1425 * @access public
1426 * @throws HTML_QuickForm_Error
1428 function hardFreezeAllVisibleExcept($elementList)
1430 $elementList = array_flip($elementList);
1431 foreach (array_keys($this->_elements) as $key) {
1432 $name = $this->_elements[$key]->getName();
1433 $type = $this->_elements[$key]->getType();
1435 if ($type == 'hidden'){
1436 // leave hidden types as they are
1437 } elseif (!isset($elementList[$name])) {
1438 $this->_elements[$key]->freeze();
1439 $this->_elements[$key]->setPersistantFreeze(false);
1441 // remove all rules
1442 $this->_rules[$name] = array();
1443 // if field is required, remove the rule
1444 $unset = array_search($name, $this->_required);
1445 if ($unset !== false) {
1446 unset($this->_required[$unset]);
1450 return true;
1453 * Tells whether the form was already submitted
1455 * This is useful since the _submitFiles and _submitValues arrays
1456 * may be completely empty after the trackSubmit value is removed.
1458 * @access public
1459 * @return bool
1461 function isSubmitted()
1463 return parent::isSubmitted() && (!$this->isFrozen());
1469 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1470 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1472 * Stylesheet is part of standard theme and should be automatically included.
1474 * @author Jamie Pratt <me@jamiep.org>
1475 * @license gpl license
1477 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1480 * Element template array
1481 * @var array
1482 * @access private
1484 var $_elementTemplates;
1486 * Template used when opening a hidden fieldset
1487 * (i.e. a fieldset that is opened when there is no header element)
1488 * @var string
1489 * @access private
1491 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1493 * Header Template string
1494 * @var string
1495 * @access private
1497 var $_headerTemplate =
1498 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1501 * Template used when opening a fieldset
1502 * @var string
1503 * @access private
1505 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1508 * Template used when closing a fieldset
1509 * @var string
1510 * @access private
1512 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1515 * Required Note template string
1516 * @var string
1517 * @access private
1519 var $_requiredNoteTemplate =
1520 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1522 var $_advancedElements = array();
1525 * Whether to display advanced elements (on page load)
1527 * @var integer 1 means show 0 means hide
1529 var $_showAdvanced;
1531 function MoodleQuickForm_Renderer(){
1532 // switch next two lines for ol li containers for form items.
1533 // $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>');
1534 $this->_elementTemplates = array(
1535 '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>',
1537 '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>',
1539 '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>',
1541 'nodisplay'=>'');
1543 parent::HTML_QuickForm_Renderer_Tableless();
1546 function setAdvancedElements($elements){
1547 $this->_advancedElements = $elements;
1551 * What to do when starting the form
1553 * @param MoodleQuickForm $form
1555 function startForm(&$form){
1556 $this->_reqHTML = $form->getReqHTML();
1557 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1558 $this->_advancedHTML = $form->getAdvancedHTML();
1559 $this->_showAdvanced = $form->getShowAdvanced();
1560 parent::startForm($form);
1561 if ($form->isFrozen()){
1562 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
1563 } else {
1564 $this->_hiddenHtml .= $form->_pageparams;
1570 function startGroup(&$group, $required, $error){
1571 if (method_exists($group, 'getElementTemplateType')){
1572 $html = $this->_elementTemplates[$group->getElementTemplateType()];
1573 }else{
1574 $html = $this->_elementTemplates['default'];
1577 if ($this->_showAdvanced){
1578 $advclass = ' advanced';
1579 } else {
1580 $advclass = ' advanced hide';
1582 if (isset($this->_advancedElements[$group->getName()])){
1583 $html =str_replace(' {advanced}', $advclass, $html);
1584 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1585 } else {
1586 $html =str_replace(' {advanced}', '', $html);
1587 $html =str_replace('{advancedimg}', '', $html);
1589 if (method_exists($group, 'getHelpButton')){
1590 $html =str_replace('{help}', $group->getHelpButton(), $html);
1591 }else{
1592 $html =str_replace('{help}', '', $html);
1594 $html =str_replace('{name}', $group->getName(), $html);
1595 $html =str_replace('{type}', 'fgroup', $html);
1597 $this->_templates[$group->getName()]=$html;
1598 // Fix for bug in tableless quickforms that didn't allow you to stop a
1599 // fieldset before a group of elements.
1600 // if the element name indicates the end of a fieldset, close the fieldset
1601 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1602 && $this->_fieldsetsOpen > 0
1604 $this->_html .= $this->_closeFieldsetTemplate;
1605 $this->_fieldsetsOpen--;
1607 parent::startGroup($group, $required, $error);
1610 function renderElement(&$element, $required, $error){
1611 //manipulate id of all elements before rendering
1612 if (!is_null($element->getAttribute('id'))) {
1613 $id = $element->getAttribute('id');
1614 } else {
1615 $id = $element->getName();
1617 //strip qf_ prefix and replace '[' with '_' and strip ']'
1618 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1619 if (strpos($id, 'id_') !== 0){
1620 $element->updateAttributes(array('id'=>'id_'.$id));
1623 //adding stuff to place holders in template
1624 if (method_exists($element, 'getElementTemplateType')){
1625 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1626 }else{
1627 $html = $this->_elementTemplates['default'];
1629 if ($this->_showAdvanced){
1630 $advclass = ' advanced';
1631 } else {
1632 $advclass = ' advanced hide';
1634 if (isset($this->_advancedElements[$element->getName()])){
1635 $html =str_replace(' {advanced}', $advclass, $html);
1636 } else {
1637 $html =str_replace(' {advanced}', '', $html);
1639 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1640 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1641 } else {
1642 $html =str_replace('{advancedimg}', '', $html);
1644 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1645 $html =str_replace('{name}', $element->getName(), $html);
1646 if (method_exists($element, 'getHelpButton')){
1647 $html = str_replace('{help}', $element->getHelpButton(), $html);
1648 }else{
1649 $html = str_replace('{help}', '', $html);
1652 if (!isset($this->_templates[$element->getName()])) {
1653 $this->_templates[$element->getName()] = $html;
1656 parent::renderElement($element, $required, $error);
1659 function finishForm(&$form){
1660 if ($form->isFrozen()){
1661 $this->_hiddenHtml = '';
1663 parent::finishForm($form);
1664 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1665 // add a lockoptions script
1666 $this->_html = $this->_html . "\n" . $script;
1670 * Called when visiting a header element
1672 * @param object An HTML_QuickForm_header element being visited
1673 * @access public
1674 * @return void
1676 function renderHeader(&$header) {
1677 $name = $header->getName();
1679 $id = empty($name) ? '' : ' id="' . $name . '"';
1680 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1681 if (is_null($header->_text)) {
1682 $header_html = '';
1683 } elseif (!empty($name) && isset($this->_templates[$name])) {
1684 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1685 } else {
1686 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1689 if (isset($this->_advancedElements[$name])){
1690 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1691 } else {
1692 $header_html =str_replace('{advancedimg}', '', $header_html);
1694 $elementName='mform_showadvanced';
1695 if ($this->_showAdvanced==0){
1696 $buttonlabel = get_string('showadvanced', 'form');
1697 } else {
1698 $buttonlabel = get_string('hideadvanced', 'form');
1701 if (isset($this->_advancedElements[$name])){
1702 $showtext="'".get_string('showadvanced', 'form')."'";
1703 $hidetext="'".get_string('hideadvanced', 'form')."'";
1704 //onclick returns false so if js is on then page is not submitted.
1705 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1706 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1707 $header_html =str_replace('{button}', $button, $header_html);
1708 } else {
1709 $header_html =str_replace('{button}', '', $header_html);
1712 if ($this->_fieldsetsOpen > 0) {
1713 $this->_html .= $this->_closeFieldsetTemplate;
1714 $this->_fieldsetsOpen--;
1717 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1718 if ($this->_showAdvanced){
1719 $advclass = ' class="advanced"';
1720 } else {
1721 $advclass = ' class="advanced hide"';
1723 if (isset($this->_advancedElements[$name])){
1724 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1725 } else {
1726 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1728 $this->_html .= $openFieldsetTemplate . $header_html;
1729 $this->_fieldsetsOpen++;
1730 } // end func renderHeader
1732 function getStopFieldsetElements(){
1733 return $this->_stopFieldsetElements;
1738 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1740 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1741 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1742 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1743 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1744 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1745 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1746 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1747 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1748 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1749 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1750 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1751 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1752 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1753 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1754 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1755 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1756 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1757 MoodleQuickForm::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
1758 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1759 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1760 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1761 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1762 MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1763 MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1764 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1765 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1766 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1767 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');