calendar/lib: calendar_set_filters() use pre-fetched context and course recs
[moodle-pu.git] / lib / formslib.php
blob05e4f9fe58095053230263df40c7f01a675cfaa4
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() {
193 if (empty($_FILES)) {
194 // we do not need to do any checks because no files were submitted
195 // TODO: find out why server side required rule does not work for uploaded files;
196 // testing is easily done by always returning true from this function and adding
197 // $mform->addRule('soubor', get_string('required'), 'required', null, 'server');
198 // and submitting form without selected file
199 return true;
201 $errors = array();
202 $mform =& $this->_form;
204 // check the files
205 $status = $this->_upload_manager->preprocess_files();
207 // now check that we really want each file
208 foreach ($_FILES as $elname=>$file) {
209 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
210 $required = $mform->isElementRequired($elname);
211 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
212 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
213 // file not uploaded and not required - ignore it
214 continue;
216 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
218 } else {
219 error('Incorrect upload attempt!');
223 // return errors if found
224 if ($status and 0 == count($errors)){
225 return true;
226 } else {
227 return $errors;
232 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
233 * form definition (new entry form); this function is used to load in data where values
234 * already exist and data is being edited (edit entry form).
236 * @param mixed $default_values object or array of default values
237 * @param bool $slased true if magic quotes applied to data values
239 function set_data($default_values, $slashed=false) {
240 if (is_object($default_values)) {
241 $default_values = (array)$default_values;
243 $filter = $slashed ? 'stripslashes' : NULL;
244 $this->_form->setDefaults($default_values, $filter);
248 * Set custom upload manager.
249 * Must be used BEFORE creating of file element!
251 * @param object $um - custom upload manager
253 function set_upload_manager($um=false) {
254 if ($um === false) {
255 $um = new upload_manager();
257 $this->_upload_manager = $um;
259 $this->_form->setMaxFileSize($um->config->maxbytes);
263 * Check that form was submitted. Does not check validity of submitted data.
265 * @return bool true if form properly submitted
267 function is_submitted() {
268 return $this->_form->isSubmitted();
271 function no_submit_button_pressed(){
272 static $nosubmit = null; // one check is enough
273 if (!is_null($nosubmit)){
274 return $nosubmit;
276 $mform =& $this->_form;
277 $nosubmit = false;
278 if (!$this->is_submitted()){
279 return false;
281 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
282 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
283 $nosubmit = true;
284 break;
287 return $nosubmit;
292 * Check that form data is valid.
294 * @return bool true if form data valid
296 function is_validated() {
297 static $validated = null; // one validation is enough
298 $mform =& $this->_form;
300 //finalize the form definition before any processing
301 if (!$this->_definition_finalized) {
302 $this->_definition_finalized = true;
303 $this->definition_after_data();
306 if ($this->no_submit_button_pressed()){
307 return false;
308 } elseif ($validated === null) {
309 $internal_val = $mform->validate();
310 $moodle_val = $this->validation($mform->exportValues(null, true));
311 if ($moodle_val !== true) {
312 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
313 foreach ($moodle_val as $element=>$msg) {
314 $mform->setElementError($element, $msg);
316 $moodle_val = false;
317 } else {
318 $moodle_val = true;
321 $file_val = $this->_validate_files();
322 if ($file_val !== true) {
323 if (!empty($file_val)) {
324 foreach ($file_val as $element=>$msg) {
325 $mform->setElementError($element, $msg);
328 $file_val = false;
330 $validated = ($internal_val and $moodle_val and $file_val);
332 return $validated;
336 * Return true if a cancel button has been pressed resulting in the form being submitted.
338 * @return boolean true if a cancel button has been pressed
340 function is_cancelled(){
341 $mform =& $this->_form;
342 if ($mform->isSubmitted()){
343 foreach ($mform->_cancelButtons as $cancelbutton){
344 if (optional_param($cancelbutton, 0, PARAM_RAW)){
345 return true;
349 return false;
353 * Return submitted data if properly submitted or returns NULL if validation fails or
354 * if there is no submitted data.
356 * @param bool $slashed true means return data with addslashes applied
357 * @return object submitted data; NULL if not valid or not submitted
359 function get_data($slashed=true) {
360 $mform =& $this->_form;
362 if ($this->is_submitted() and $this->is_validated()) {
363 $data = $mform->exportValues(null, $slashed);
364 unset($data['sesskey']); // we do not need to return sesskey
365 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
366 if (empty($data)) {
367 return NULL;
368 } else {
369 return (object)$data;
371 } else {
372 return NULL;
377 * Return submitted data without validation or NULL if there is no submitted data.
379 * @param bool $slashed true means return data with addslashes applied
380 * @return object submitted data; NULL if not submitted
382 function get_submitted_data($slashed=true) {
383 $mform =& $this->_form;
385 if ($this->is_submitted()) {
386 $data = $mform->exportValues(null, $slashed);
387 unset($data['sesskey']); // we do not need to return sesskey
388 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
389 if (empty($data)) {
390 return NULL;
391 } else {
392 return (object)$data;
394 } else {
395 return NULL;
400 * Save verified uploaded files into directory. Upload process can be customised from definition()
401 * method by creating instance of upload manager and storing it in $this->_upload_form
403 * @param string $destination where to store uploaded files
404 * @return bool success
406 function save_files($destination) {
407 if ($this->is_submitted() and $this->is_validated()) {
408 return $this->_upload_manager->save_files($destination);
410 return false;
414 * If we're only handling one file (if inputname was given in the constructor)
415 * this will return the (possibly changed) filename of the file.
416 * @return mixed false in case of failure, string if ok
418 function get_new_filename() {
419 return $this->_upload_manager->get_new_filename();
423 * Print html form.
425 function display() {
426 //finalize the form definition if not yet done
427 if (!$this->_definition_finalized) {
428 $this->_definition_finalized = true;
429 $this->definition_after_data();
431 $this->_form->display();
435 * Abstract method - always override!
437 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
439 function definition() {
440 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
444 * Dummy stub method - override if you need to setup the form depending on current
445 * values. This method is called after definition(), data submission and set_data().
446 * All form setup that is dependent on form values should go in here.
448 function definition_after_data(){
452 * Dummy stub method - override if you needed to perform some extra validation.
453 * If there are errors return array of errors ("fieldname"=>"error message"),
454 * otherwise true if ok.
456 * @param array $data array of ("fieldname"=>value) of submitted data
457 * @return bool array of errors or true if ok
459 function validation($data) {
460 return array();
464 * Method to add a repeating group of elements to a form.
466 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
467 * @param integer $repeats no of times to repeat elements initially
468 * @param array $options Array of options to apply to elements. Array keys are element names.
469 * This is an array of arrays. The second sets of keys are the option types
470 * for the elements :
471 * 'default' - default value is value
472 * 'type' - PARAM_* constant is value
473 * 'helpbutton' - helpbutton params array is value
474 * 'disabledif' - last three moodleform::disabledIf()
475 * params are value as an array
476 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
477 * @param string $addfieldsname name for button to add more fields
478 * @param int $addfieldsno how many fields to add at a time
479 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
480 * @return int no of repeats of element in this page
482 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, $addfieldsname, $addfieldsno=5, $addstring=null){
483 if ($addstring===null){
484 $addstring = get_string('addfields', 'form', $addfieldsno);
485 } else {
486 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
488 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
489 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
490 if (!empty($addfields)){
491 $repeats += $addfieldsno;
493 $mform =& $this->_form;
494 $mform->registerNoSubmitButton($addfieldsname);
495 $mform->addElement('hidden', $repeathiddenname, $repeats);
496 //value not to be overridden by submitted value
497 $mform->setConstants(array($repeathiddenname=>$repeats));
498 for ($i=0; $i<$repeats; $i++) {
499 foreach ($elementobjs as $elementobj){
500 $elementclone = clone($elementobj);
501 $name = $elementclone->getName();
502 if (!empty($name)){
503 $elementclone->setName($name."[$i]");
505 if (is_a($elementclone, 'HTML_QuickForm_header')){
506 $value=$elementclone->_text;
507 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
509 } else {
510 $value=$elementclone->getLabel();
511 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
515 $mform->addElement($elementclone);
518 for ($i=0; $i<$repeats; $i++) {
519 foreach ($options as $elementname => $elementoptions){
520 $pos=strpos($elementname, '[');
521 if ($pos!==FALSE){
522 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
523 $realelementname .= substr($elementname, $pos+1);
524 }else {
525 $realelementname = $elementname."[$i]";
527 foreach ($elementoptions as $option => $params){
529 switch ($option){
530 case 'default' :
531 $mform->setDefault($realelementname, $params);
532 break;
533 case 'helpbutton' :
534 $mform->setHelpButton($realelementname, $params);
535 break;
536 case 'disabledif' :
537 $params = array_merge(array($realelementname), $params);
538 call_user_func_array(array(&$mform, 'disabledIf'), $params);
539 break;
540 case 'rule' :
541 if (is_string($params)){
542 $params = array(null, $params, null, 'client');
544 $params = array_merge(array($realelementname), $params);
545 call_user_func_array(array(&$mform, 'addRule'), $params);
546 break;
552 $mform->addElement('submit', $addfieldsname, $addstring);
554 $mform->closeHeaderBefore($addfieldsname);
556 return $repeats;
559 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
560 * if you don't want a cancel button in your form. If you have a cancel button make sure you
561 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
562 * get data with get_data().
564 * @param boolean $cancel whether to show cancel button, default true
565 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
567 function add_action_buttons($cancel = true, $submitlabel=null){
568 if (is_null($submitlabel)){
569 $submitlabel = get_string('savechanges');
571 $mform =& $this->_form;
572 if ($cancel){
573 //when two elements we need a group
574 $buttonarray=array();
575 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
576 $buttonarray[] = &$mform->createElement('cancel');
577 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
578 $mform->closeHeaderBefore('buttonar');
579 } else {
580 //no group needed
581 $mform->addElement('submit', 'submitbutton', $submitlabel);
582 $mform->closeHeaderBefore('submitbutton');
588 * You never extend this class directly. The class methods of this class are available from
589 * the private $this->_form property on moodleform and it's children. You generally only
590 * call methods on this class from within abstract methods that you override on moodleform such
591 * as definition and definition_after_data
594 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
595 var $_types = array();
596 var $_dependencies = array();
598 * Array of buttons that if pressed do not result in the processing of the form.
600 * @var array
602 var $_noSubmitButtons=array();
604 * Array of buttons that if pressed do not result in the processing of the form.
606 * @var array
608 var $_cancelButtons=array();
611 * Array whose keys are element names. If the key exists this is a advanced element
613 * @var array
615 var $_advancedElements = array();
618 * Whether to display advanced elements (on page load)
620 * @var boolean
622 var $_showAdvanced = null;
625 * The form name is derrived from the class name of the wrapper minus the trailing form
626 * It is a name with words joined by underscores whereas the id attribute is words joined by
627 * underscores.
629 * @var unknown_type
631 var $_formName = '';
634 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
636 * @var string
638 var $_pageparams = '';
641 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
642 * @param string $formName Form's name.
643 * @param string $method (optional)Form's method defaults to 'POST'
644 * @param mixed $action (optional)Form's action - string or moodle_url
645 * @param string $target (optional)Form's target defaults to none
646 * @param mixed $attributes (optional)Extra attributes for <form> tag
647 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
648 * @access public
650 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
651 global $CFG;
653 static $formcounter = 1;
655 HTML_Common::HTML_Common($attributes);
656 $target = empty($target) ? array() : array('target' => $target);
657 $this->_formName = $formName;
658 if (is_a($action, 'moodle_url')){
659 $this->_pageparams = $action->hidden_params_out();
660 $action = $action->out(true);
661 } else {
662 $this->_pageparams = '';
664 //no 'name' atttribute for form in xhtml strict :
665 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
666 $formcounter++;
667 $this->updateAttributes($attributes);
669 //this is custom stuff for Moodle :
670 $oldclass= $this->getAttribute('class');
671 if (!empty($oldclass)){
672 $this->updateAttributes(array('class'=>$oldclass.' mform'));
673 }else {
674 $this->updateAttributes(array('class'=>'mform'));
676 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
677 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
678 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
679 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
683 * Use this method to indicate an element in a form is an advanced field. If items in a form
684 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
685 * form so the user can decide whether to display advanced form controls.
687 * If you set a header element to advanced then all elements it contains will also be set as advanced.
689 * @param string $elementName group or element name (not the element name of something inside a group).
690 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
692 function setAdvanced($elementName, $advanced=true){
693 if ($advanced){
694 $this->_advancedElements[$elementName]='';
695 } elseif (isset($this->_advancedElements[$elementName])) {
696 unset($this->_advancedElements[$elementName]);
698 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
699 $this->setShowAdvanced();
700 $this->registerNoSubmitButton('mform_showadvanced');
702 $this->addElement('hidden', 'mform_showadvanced_last');
706 * Set whether to show advanced elements in the form on first displaying form. Default is not to
707 * display advanced elements in the form until 'Show Advanced' is pressed.
709 * You can get the last state of the form and possibly save it for this user by using
710 * value 'mform_showadvanced_last' in submitted data.
712 * @param boolean $showadvancedNow
714 function setShowAdvanced($showadvancedNow = null){
715 if ($showadvancedNow === null){
716 if ($this->_showAdvanced !== null){
717 return;
718 } else { //if setShowAdvanced is called without any preference
719 //make the default to not show advanced elements.
720 $showadvancedNow = get_user_preferences(
721 moodle_strtolower($this->_formName.'_showadvanced', 0));
724 //value of hidden element
725 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
726 //value of button
727 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
728 //toggle if button pressed or else stay the same
729 if ($hiddenLast == -1) {
730 $next = $showadvancedNow;
731 } elseif ($buttonPressed) { //toggle on button press
732 $next = !$hiddenLast;
733 } else {
734 $next = $hiddenLast;
736 $this->_showAdvanced = $next;
737 if ($showadvancedNow != $next){
738 set_user_preference($this->_formName.'_showadvanced', $next);
740 $this->setConstants(array('mform_showadvanced_last'=>$next));
742 function getShowAdvanced(){
743 return $this->_showAdvanced;
748 * Accepts a renderer
750 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
751 * @since 3.0
752 * @access public
753 * @return void
755 function accept(&$renderer)
757 if (method_exists($renderer, 'setAdvancedElements')){
758 //check for visible fieldsets where all elements are advanced
759 //and mark these headers as advanced as well.
760 //And mark all elements in a advanced header as advanced
761 $stopFields = $renderer->getStopFieldSetElements();
762 $lastHeader = null;
763 $lastHeaderAdvanced = false;
764 $anyAdvanced = false;
765 foreach (array_keys($this->_elements) as $elementIndex){
766 $element =& $this->_elements[$elementIndex];
767 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
768 if ($anyAdvanced && ($lastHeader!==null)){
769 $this->setAdvanced($lastHeader->getName());
771 $lastHeaderAdvanced = false;
772 } elseif ($lastHeaderAdvanced) {
773 $this->setAdvanced($element->getName());
775 if ($element->getType()=='header'){
776 $lastHeader =& $element;
777 $anyAdvanced = false;
778 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
779 } elseif (isset($this->_advancedElements[$element->getName()])){
780 $anyAdvanced = true;
783 $renderer->setAdvancedElements($this->_advancedElements);
786 parent::accept($renderer);
791 function closeHeaderBefore($elementName){
792 $renderer =& $this->defaultRenderer();
793 $renderer->addStopFieldsetElements($elementName);
797 * Should be used for all elements of a form except for select, radio and checkboxes which
798 * clean their own data.
800 * @param string $elementname
801 * @param integer $paramtype use the constants PARAM_*.
802 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
803 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
804 * It will strip all html tags. But will still let tags for multilang support
805 * through.
806 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
807 * html editor. Data from the editor is later cleaned before display using
808 * format_text() function. PARAM_RAW can also be used for data that is validated
809 * by some other way or printed by p() or s().
810 * * PARAM_INT should be used for integers.
811 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
812 * form actions.
814 function setType($elementname, $paramtype) {
815 $this->_types[$elementname] = $paramtype;
819 * See description of setType above. This can be used to set several types at once.
821 * @param array $paramtypes
823 function setTypes($paramtypes) {
824 $this->_types = $paramtypes + $this->_types;
827 function updateSubmission($submission, $files) {
828 $this->_flagSubmitted = false;
830 if (empty($submission)) {
831 $this->_submitValues = array();
832 } else {
833 foreach ($submission as $key=>$s) {
834 if (array_key_exists($key, $this->_types)) {
835 $submission[$key] = clean_param($s, $this->_types[$key]);
838 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
839 $this->_flagSubmitted = true;
842 if (empty($files)) {
843 $this->_submitFiles = array();
844 } else {
845 if (1 == get_magic_quotes_gpc()) {
846 foreach (array_keys($files) as $elname) {
847 // dangerous characters in filenames are cleaned later in upload_manager
848 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
851 $this->_submitFiles = $files;
852 $this->_flagSubmitted = true;
855 // need to tell all elements that they need to update their value attribute.
856 foreach (array_keys($this->_elements) as $key) {
857 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
861 function getReqHTML(){
862 return $this->_reqHTML;
865 function getAdvancedHTML(){
866 return $this->_advancedHTML;
870 * Initializes a default form value. Used to specify the default for a new entry where
871 * no data is loaded in using moodleform::set_data()
873 * @param string $elementname element name
874 * @param mixed $values values for that element name
875 * @param bool $slashed the default value is slashed
876 * @access public
877 * @return void
879 function setDefault($elementName, $defaultValue, $slashed=false){
880 $filter = $slashed ? 'stripslashes' : NULL;
881 $this->setDefaults(array($elementName=>$defaultValue), $filter);
882 } // end func setDefault
884 * Add an array of buttons to the form
885 * @param array $buttons An associative array representing help button to attach to
886 * to the form. keys of array correspond to names of elements in form.
888 * @access public
890 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
892 foreach ($buttons as $elementname => $button){
893 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
897 * Add a single button.
899 * @param string $elementname name of the element to add the item to
900 * @param array $button - arguments to pass to function $function
901 * @param boolean $suppresscheck - whether to throw an error if the element
902 * doesn't exist.
903 * @param string $function - function to generate html from the arguments in $button
905 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
906 if (array_key_exists($elementname, $this->_elementIndex)){
907 //_elements has a numeric index, this code accesses the elements by name
908 $element=&$this->_elements[$this->_elementIndex[$elementname]];
909 if (method_exists($element, 'setHelpButton')){
910 $element->setHelpButton($button, $function);
911 }else{
912 $a=new object();
913 $a->name=$element->getName();
914 $a->classname=get_class($element);
915 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
917 }elseif (!$suppresscheck){
918 print_error('nonexistentformelements', 'form', '', $elementname);
922 function exportValues($elementList= null, $addslashes=true){
923 $unfiltered = array();
924 if (null === $elementList) {
925 // iterate over all elements, calling their exportValue() methods
926 $emptyarray = array();
927 foreach (array_keys($this->_elements) as $key) {
928 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
929 $value = $this->_elements[$key]->exportValue($emptyarray, true);
930 } else {
931 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
934 if (is_array($value)) {
935 // This shit throws a bogus warning in PHP 4.3.x
936 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
939 } else {
940 if (!is_array($elementList)) {
941 $elementList = array_map('trim', explode(',', $elementList));
943 foreach ($elementList as $elementName) {
944 $value = $this->exportValue($elementName);
945 if (PEAR::isError($value)) {
946 return $value;
948 $unfiltered[$elementName] = $value;
952 if ($addslashes){
953 return $this->_recursiveFilter('addslashes', $unfiltered);
954 } else {
955 return $unfiltered;
959 * Adds a validation rule for the given field
961 * If the element is in fact a group, it will be considered as a whole.
962 * To validate grouped elements as separated entities,
963 * use addGroupRule instead of addRule.
965 * @param string $element Form element name
966 * @param string $message Message to display for invalid data
967 * @param string $type Rule type, use getRegisteredRules() to get types
968 * @param string $format (optional)Required for extra rule data
969 * @param string $validation (optional)Where to perform validation: "server", "client"
970 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
971 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
972 * @since 1.0
973 * @access public
974 * @throws HTML_QuickForm_Error
976 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
978 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
979 if ($validation == 'client') {
980 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
983 } // end func addRule
985 * Adds a validation rule for the given group of elements
987 * Only groups with a name can be assigned a validation rule
988 * Use addGroupRule when you need to validate elements inside the group.
989 * Use addRule if you need to validate the group as a whole. In this case,
990 * the same rule will be applied to all elements in the group.
991 * Use addRule if you need to validate the group against a function.
993 * @param string $group Form group name
994 * @param mixed $arg1 Array for multiple elements or error message string for one element
995 * @param string $type (optional)Rule type use getRegisteredRules() to get types
996 * @param string $format (optional)Required for extra rule data
997 * @param int $howmany (optional)How many valid elements should be in the group
998 * @param string $validation (optional)Where to perform validation: "server", "client"
999 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1000 * @since 2.5
1001 * @access public
1002 * @throws HTML_QuickForm_Error
1004 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1006 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1007 if (is_array($arg1)) {
1008 foreach ($arg1 as $rules) {
1009 foreach ($rules as $rule) {
1010 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1012 if ('client' == $validation) {
1013 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1017 } elseif (is_string($arg1)) {
1019 if ($validation == 'client') {
1020 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1023 } // end func addGroupRule
1025 // }}}
1027 * Returns the client side validation script
1029 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1030 * and slightly modified to run rules per-element
1031 * Needed to override this because of an error with client side validation of grouped elements.
1033 * @access public
1034 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1036 function getValidationScript()
1038 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1039 return '';
1042 include_once('HTML/QuickForm/RuleRegistry.php');
1043 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1044 $test = array();
1045 $js_escape = array(
1046 "\r" => '\r',
1047 "\n" => '\n',
1048 "\t" => '\t',
1049 "'" => "\\'",
1050 '"' => '\"',
1051 '\\' => '\\\\'
1054 foreach ($this->_rules as $elementName => $rules) {
1055 foreach ($rules as $rule) {
1056 if ('client' == $rule['validation']) {
1057 unset($element); //TODO: find out how to properly initialize it
1059 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1060 $rule['message'] = strtr($rule['message'], $js_escape);
1062 if (isset($rule['group'])) {
1063 $group =& $this->getElement($rule['group']);
1064 // No JavaScript validation for frozen elements
1065 if ($group->isFrozen()) {
1066 continue 2;
1068 $elements =& $group->getElements();
1069 foreach (array_keys($elements) as $key) {
1070 if ($elementName == $group->getElementName($key)) {
1071 $element =& $elements[$key];
1072 break;
1075 } elseif ($dependent) {
1076 $element = array();
1077 $element[] =& $this->getElement($elementName);
1078 foreach ($rule['dependent'] as $elName) {
1079 $element[] =& $this->getElement($elName);
1081 } else {
1082 $element =& $this->getElement($elementName);
1084 // No JavaScript validation for frozen elements
1085 if (is_object($element) && $element->isFrozen()) {
1086 continue 2;
1087 } elseif (is_array($element)) {
1088 foreach (array_keys($element) as $key) {
1089 if ($element[$key]->isFrozen()) {
1090 continue 3;
1094 // Fix for bug displaying errors for elements in a group
1095 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1096 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1097 $test[$elementName][1]=$element;
1098 //end of fix
1103 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1104 // the form, and then that form field gets corrupted by the code that follows.
1105 unset($element);
1107 $js = '
1108 <script type="text/javascript">
1109 //<![CDATA[
1111 var skipClientValidation = false;
1113 function qf_errorHandler(element, _qfMsg) {
1114 div = element.parentNode;
1115 if (_qfMsg != \'\') {
1116 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1117 if (!errorSpan) {
1118 errorSpan = document.createElement("span");
1119 errorSpan.id = \'id_error_\'+element.name;
1120 errorSpan.className = "error";
1121 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1124 while (errorSpan.firstChild) {
1125 errorSpan.removeChild(errorSpan.firstChild);
1128 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1129 errorSpan.appendChild(document.createElement("br"));
1131 if (div.className.substr(div.className.length - 6, 6) != " error"
1132 && div.className != "error") {
1133 div.className += " error";
1136 return false;
1137 } else {
1138 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1139 if (errorSpan) {
1140 errorSpan.parentNode.removeChild(errorSpan);
1143 if (div.className.substr(div.className.length - 6, 6) == " error") {
1144 div.className = div.className.substr(0, div.className.length - 6);
1145 } else if (div.className == "error") {
1146 div.className = "";
1149 return true;
1152 $validateJS = '';
1153 foreach ($test as $elementName => $jsandelement) {
1154 // Fix for bug displaying errors for elements in a group
1155 //unset($element);
1156 list($jsArr,$element)=$jsandelement;
1157 //end of fix
1158 $js .= '
1159 function validate_' . $this->_formName . '_' . $elementName . '(element) {
1160 var value = \'\';
1161 var errFlag = new Array();
1162 var _qfGroups = {};
1163 var _qfMsg = \'\';
1164 var frm = element.parentNode;
1165 while (frm && frm.nodeName != "FORM") {
1166 frm = frm.parentNode;
1168 ' . join("\n", $jsArr) . '
1169 return qf_errorHandler(element, _qfMsg);
1172 $validateJS .= '
1173 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1174 if (!ret && !first_focus) {
1175 first_focus = true;
1176 frm.elements[\''.$elementName.'\'].focus();
1180 // Fix for bug displaying errors for elements in a group
1181 //unset($element);
1182 //$element =& $this->getElement($elementName);
1183 //end of fix
1184 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
1185 $onBlur = $element->getAttribute('onBlur');
1186 $onChange = $element->getAttribute('onChange');
1187 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1188 'onChange' => $onChange . $valFunc));
1190 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1191 $js .= '
1192 function validate_' . $this->_formName . '(frm) {
1193 if (skipClientValidation) {
1194 return true;
1196 var ret = true;
1198 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1199 var first_focus = false;
1200 ' . $validateJS . ';
1201 return ret;
1203 //]]>
1204 </script>';
1205 return $js;
1206 } // end func getValidationScript
1207 function _setDefaultRuleMessages(){
1208 foreach ($this->_rules as $field => $rulesarr){
1209 foreach ($rulesarr as $key => $rule){
1210 if ($rule['message']===null){
1211 $a=new object();
1212 $a->format=$rule['format'];
1213 $str=get_string('err_'.$rule['type'], 'form', $a);
1214 if (strpos($str, '[[')!==0){
1215 $this->_rules[$field][$key]['message']=$str;
1222 function getLockOptionEndScript(){
1224 $iname = $this->getAttribute('id').'items';
1225 $js = '<script type="text/javascript">'."\n";
1226 $js .= '//<![CDATA['."\n";
1227 $js .= "var $iname = Array();\n";
1229 foreach ($this->_dependencies as $dependentOn => $conditions){
1230 $js .= "{$iname}['$dependentOn'] = Array();\n";
1231 foreach ($conditions as $condition=>$values) {
1232 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1233 foreach ($values as $value=>$dependents) {
1234 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1235 $i = 0;
1236 foreach ($dependents as $dependent) {
1237 $elements = $this->_getElNamesRecursive($dependent);
1238 foreach($elements as $element) {
1239 if ($element == $dependentOn) {
1240 continue;
1242 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1243 $i++;
1249 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1250 $js .='//]]>'."\n";
1251 $js .='</script>'."\n";
1252 return $js;
1255 function _getElNamesRecursive($element, $group=null){
1256 if ($group==null){
1257 if (!$this->elementExists($element)) {
1258 return array();
1260 $el = $this->getElement($element);
1261 } else {
1262 $el = &$element;
1264 if (is_a($el, 'HTML_QuickForm_group')){
1265 $group = $el;
1266 $elsInGroup = $group->getElements();
1267 $elNames = array();
1268 foreach ($elsInGroup as $elInGroup){
1269 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1271 }else{
1272 if ($group != null){
1273 $elNames = array($group->getElementName($el->getName()));
1274 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1275 return null;
1276 } elseif (is_a($el, 'HTML_QuickForm_hidden')) {
1277 return null;
1278 } elseif (method_exists($el, 'getPrivateName')) {
1279 return array($el->getPrivateName());
1280 } else {
1281 $elNames = array($el->getName());
1284 return $elNames;
1288 * Adds a dependency for $elementName which will be disabled if $condition is met.
1289 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1290 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1291 * is checked. If $condition is something else then it is checked to see if the value
1292 * of the $dependentOn element is equal to $condition.
1294 * @param string $elementName the name of the element which will be disabled
1295 * @param string $dependentOn the name of the element whose state will be checked for
1296 * condition
1297 * @param string $condition the condition to check
1298 * @param mixed $value used in conjunction with condition.
1300 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1301 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1302 $this->_dependencies[$dependentOn] = array();
1304 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1305 $this->_dependencies[$dependentOn][$condition] = array();
1307 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1308 $this->_dependencies[$dependentOn][$condition][$value] = array();
1310 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1313 function registerNoSubmitButton($buttonname){
1314 $this->_noSubmitButtons[]=$buttonname;
1317 function isNoSubmitButton($buttonname){
1318 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1321 function _registerCancelButton($addfieldsname){
1322 $this->_cancelButtons[]=$addfieldsname;
1325 * Displays elements without HTML input tags.
1326 * This method is different to freeze() in that it makes sure no hidden
1327 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1328 * ignored.
1330 * This function also removes all previously defined rules.
1332 * @param mixed $elementList array or string of element(s) to be frozen
1333 * @since 1.0
1334 * @access public
1335 * @throws HTML_QuickForm_Error
1337 function hardFreeze($elementList=null)
1339 if (!isset($elementList)) {
1340 $this->_freezeAll = true;
1341 $elementList = array();
1342 } else {
1343 if (!is_array($elementList)) {
1344 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1346 $elementList = array_flip($elementList);
1349 foreach (array_keys($this->_elements) as $key) {
1350 $name = $this->_elements[$key]->getName();
1351 if ($this->_freezeAll || isset($elementList[$name])) {
1352 $this->_elements[$key]->freeze();
1353 $this->_elements[$key]->setPersistantFreeze(false);
1354 unset($elementList[$name]);
1356 // remove all rules
1357 $this->_rules[$name] = array();
1358 // if field is required, remove the rule
1359 $unset = array_search($name, $this->_required);
1360 if ($unset !== false) {
1361 unset($this->_required[$unset]);
1366 if (!empty($elementList)) {
1367 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);
1369 return true;
1372 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1374 * This function also removes all previously defined rules of elements it freezes.
1376 * @param array $elementList array or string of element(s) not to be frozen
1377 * @since 1.0
1378 * @access public
1379 * @throws HTML_QuickForm_Error
1381 function hardFreezeAllVisibleExcept($elementList)
1383 $elementList = array_flip($elementList);
1384 foreach (array_keys($this->_elements) as $key) {
1385 $name = $this->_elements[$key]->getName();
1386 $type = $this->_elements[$key]->getType();
1388 if ($type == 'hidden'){
1389 // leave hidden types as they are
1390 } elseif (!isset($elementList[$name])) {
1391 $this->_elements[$key]->freeze();
1392 $this->_elements[$key]->setPersistantFreeze(false);
1394 // remove all rules
1395 $this->_rules[$name] = array();
1396 // if field is required, remove the rule
1397 $unset = array_search($name, $this->_required);
1398 if ($unset !== false) {
1399 unset($this->_required[$unset]);
1403 return true;
1406 * Tells whether the form was already submitted
1408 * This is useful since the _submitFiles and _submitValues arrays
1409 * may be completely empty after the trackSubmit value is removed.
1411 * @access public
1412 * @return bool
1414 function isSubmitted()
1416 return parent::isSubmitted() && (!$this->isFrozen());
1422 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1423 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1425 * Stylesheet is part of standard theme and should be automatically included.
1427 * @author Jamie Pratt <me@jamiep.org>
1428 * @license gpl license
1430 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1433 * Element template array
1434 * @var array
1435 * @access private
1437 var $_elementTemplates;
1439 * Template used when opening a hidden fieldset
1440 * (i.e. a fieldset that is opened when there is no header element)
1441 * @var string
1442 * @access private
1444 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1446 * Header Template string
1447 * @var string
1448 * @access private
1450 var $_headerTemplate =
1451 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1454 * Template used when opening a fieldset
1455 * @var string
1456 * @access private
1458 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1461 * Template used when closing a fieldset
1462 * @var string
1463 * @access private
1465 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1468 * Required Note template string
1469 * @var string
1470 * @access private
1472 var $_requiredNoteTemplate =
1473 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1475 var $_advancedElements = array();
1478 * Whether to display advanced elements (on page load)
1480 * @var integer 1 means show 0 means hide
1482 var $_showAdvanced;
1484 function MoodleQuickForm_Renderer(){
1485 // switch next two lines for ol li containers for form items.
1486 // $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>');
1487 $this->_elementTemplates = array(
1488 '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>',
1490 '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>',
1492 '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>',
1494 'nodisplay'=>'');
1496 parent::HTML_QuickForm_Renderer_Tableless();
1499 function setAdvancedElements($elements){
1500 $this->_advancedElements = $elements;
1504 * What to do when starting the form
1506 * @param MoodleQuickForm $form
1508 function startForm(&$form){
1509 $this->_reqHTML = $form->getReqHTML();
1510 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1511 $this->_advancedHTML = $form->getAdvancedHTML();
1512 $this->_showAdvanced = $form->getShowAdvanced();
1513 parent::startForm($form);
1514 if ($form->isFrozen()){
1515 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
1516 } else {
1517 $this->_hiddenHtml .= $form->_pageparams;
1523 function startGroup(&$group, $required, $error){
1524 if (method_exists($group, 'getElementTemplateType')){
1525 $html = $this->_elementTemplates[$group->getElementTemplateType()];
1526 }else{
1527 $html = $this->_elementTemplates['default'];
1530 if ($this->_showAdvanced){
1531 $advclass = ' advanced';
1532 } else {
1533 $advclass = ' advanced hide';
1535 if (isset($this->_advancedElements[$group->getName()])){
1536 $html =str_replace(' {advanced}', $advclass, $html);
1537 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1538 } else {
1539 $html =str_replace(' {advanced}', '', $html);
1540 $html =str_replace('{advancedimg}', '', $html);
1542 if (method_exists($group, 'getHelpButton')){
1543 $html =str_replace('{help}', $group->getHelpButton(), $html);
1544 }else{
1545 $html =str_replace('{help}', '', $html);
1547 $html =str_replace('{name}', $group->getName(), $html);
1548 $html =str_replace('{type}', 'fgroup', $html);
1550 $this->_templates[$group->getName()]=$html;
1551 // Fix for bug in tableless quickforms that didn't allow you to stop a
1552 // fieldset before a group of elements.
1553 // if the element name indicates the end of a fieldset, close the fieldset
1554 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1555 && $this->_fieldsetsOpen > 0
1557 $this->_html .= $this->_closeFieldsetTemplate;
1558 $this->_fieldsetsOpen--;
1560 parent::startGroup($group, $required, $error);
1563 function renderElement(&$element, $required, $error){
1564 //manipulate id of all elements before rendering
1565 if (!is_null($element->getAttribute('id'))) {
1566 $id = $element->getAttribute('id');
1567 } else {
1568 $id = $element->getName();
1570 //strip qf_ prefix and replace '[' with '_' and strip ']'
1571 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1572 if (strpos($id, 'id_') !== 0){
1573 $element->updateAttributes(array('id'=>'id_'.$id));
1576 //adding stuff to place holders in template
1577 if (method_exists($element, 'getElementTemplateType')){
1578 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1579 }else{
1580 $html = $this->_elementTemplates['default'];
1582 if ($this->_showAdvanced){
1583 $advclass = ' advanced';
1584 } else {
1585 $advclass = ' advanced hide';
1587 if (isset($this->_advancedElements[$element->getName()])){
1588 $html =str_replace(' {advanced}', $advclass, $html);
1589 } else {
1590 $html =str_replace(' {advanced}', '', $html);
1592 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1593 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1594 } else {
1595 $html =str_replace('{advancedimg}', '', $html);
1597 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1598 $html =str_replace('{name}', $element->getName(), $html);
1599 if (method_exists($element, 'getHelpButton')){
1600 $html = str_replace('{help}', $element->getHelpButton(), $html);
1601 }else{
1602 $html = str_replace('{help}', '', $html);
1605 if (!isset($this->_templates[$element->getName()])) {
1606 $this->_templates[$element->getName()] = $html;
1609 parent::renderElement($element, $required, $error);
1612 function finishForm(&$form){
1613 if ($form->isFrozen()){
1614 $this->_hiddenHtml = '';
1616 parent::finishForm($form);
1617 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1618 // add a lockoptions script
1619 $this->_html = $this->_html . "\n" . $script;
1623 * Called when visiting a header element
1625 * @param object An HTML_QuickForm_header element being visited
1626 * @access public
1627 * @return void
1629 function renderHeader(&$header) {
1630 $name = $header->getName();
1632 $id = empty($name) ? '' : ' id="' . $name . '"';
1633 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1634 if (is_null($header->_text)) {
1635 $header_html = '';
1636 } elseif (!empty($name) && isset($this->_templates[$name])) {
1637 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1638 } else {
1639 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1642 if (isset($this->_advancedElements[$name])){
1643 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1644 } else {
1645 $header_html =str_replace('{advancedimg}', '', $header_html);
1647 $elementName='mform_showadvanced';
1648 if ($this->_showAdvanced==0){
1649 $buttonlabel = get_string('showadvanced', 'form');
1650 } else {
1651 $buttonlabel = get_string('hideadvanced', 'form');
1654 if (isset($this->_advancedElements[$name])){
1655 $showtext="'".get_string('showadvanced', 'form')."'";
1656 $hidetext="'".get_string('hideadvanced', 'form')."'";
1657 //onclick returns false so if js is on then page is not submitted.
1658 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1659 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1660 $header_html =str_replace('{button}', $button, $header_html);
1661 } else {
1662 $header_html =str_replace('{button}', '', $header_html);
1665 if ($this->_fieldsetsOpen > 0) {
1666 $this->_html .= $this->_closeFieldsetTemplate;
1667 $this->_fieldsetsOpen--;
1670 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1671 if ($this->_showAdvanced){
1672 $advclass = ' class="advanced"';
1673 } else {
1674 $advclass = ' class="advanced hide"';
1676 if (isset($this->_advancedElements[$name])){
1677 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1678 } else {
1679 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1681 $this->_html .= $openFieldsetTemplate . $header_html;
1682 $this->_fieldsetsOpen++;
1683 } // end func renderHeader
1685 function getStopFieldsetElements(){
1686 return $this->_stopFieldsetElements;
1691 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1693 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1694 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1695 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1696 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1697 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1698 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1699 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1700 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1701 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1702 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1703 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1704 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1705 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1706 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1707 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1708 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1709 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1710 MoodleQuickForm::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
1711 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1712 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1713 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1714 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1715 MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1716 MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1717 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1718 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1719 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1720 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');