Automatic installer.php lang files by installer_builder (20070726)
[moodle-linuxchix.git] / lib / formslib.php
blob6bc9cfe48e8a052bd591c30638f19b44ca3926d8
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 boolean $revert whether to show revert button, default true
566 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
568 function add_action_buttons($cancel = true, $submitlabel=null){
569 if (is_null($submitlabel)){
570 $submitlabel = get_string('savechanges');
572 $mform =& $this->_form;
573 if ($cancel){
574 //when two elements we need a group
575 $buttonarray=array();
576 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
577 $buttonarray[] = &$mform->createElement('cancel');
578 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
579 $mform->closeHeaderBefore('buttonar');
580 } else {
581 //no group needed
582 $mform->addElement('submit', 'submitbutton', $submitlabel);
583 $mform->closeHeaderBefore('submitbutton');
589 * You never extend this class directly. The class methods of this class are available from
590 * the private $this->_form property on moodleform and it's children. You generally only
591 * call methods on this class from within abstract methods that you override on moodleform such
592 * as definition and definition_after_data
595 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
596 var $_types = array();
597 var $_dependencies = array();
599 * Array of buttons that if pressed do not result in the processing of the form.
601 * @var array
603 var $_noSubmitButtons=array();
605 * Array of buttons that if pressed do not result in the processing of the form.
607 * @var array
609 var $_cancelButtons=array();
612 * Array whose keys are element names. If the key exists this is a advanced element
614 * @var array
616 var $_advancedElements = array();
619 * Whether to display advanced elements (on page load)
621 * @var boolean
623 var $_showAdvanced = null;
626 * The form name is derrived from the class name of the wrapper minus the trailing form
627 * It is a name with words joined by underscores whereas the id attribute is words joined by
628 * underscores.
630 * @var unknown_type
632 var $_formName = '';
635 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
637 * @var string
639 var $_pageparams = '';
642 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
643 * @param string $formName Form's name.
644 * @param string $method (optional)Form's method defaults to 'POST'
645 * @param mixed $action (optional)Form's action - string or moodle_url
646 * @param string $target (optional)Form's target defaults to none
647 * @param mixed $attributes (optional)Extra attributes for <form> tag
648 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
649 * @access public
651 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
652 global $CFG;
654 static $formcounter = 1;
656 HTML_Common::HTML_Common($attributes);
657 $target = empty($target) ? array() : array('target' => $target);
658 $this->_formName = $formName;
659 if (is_a($action, 'moodle_url')){
660 $this->_pageparams = $action->hidden_params_out();
661 $action = $action->out(true);
662 } else {
663 $this->_pageparams = '';
665 //no 'name' atttribute for form in xhtml strict :
666 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
667 $formcounter++;
668 $this->updateAttributes($attributes);
670 //this is custom stuff for Moodle :
671 $oldclass= $this->getAttribute('class');
672 if (!empty($oldclass)){
673 $this->updateAttributes(array('class'=>$oldclass.' mform'));
674 }else {
675 $this->updateAttributes(array('class'=>'mform'));
677 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
678 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
679 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
680 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
684 * Use this method to indicate an element in a form is an advanced field. If items in a form
685 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
686 * form so the user can decide whether to display advanced form controls.
688 * If you set a header element to advanced then all elements it contains will also be set as advanced.
690 * @param string $elementName group or element name (not the element name of something inside a group).
691 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
693 function setAdvanced($elementName, $advanced=true){
694 if ($advanced){
695 $this->_advancedElements[$elementName]='';
696 } elseif (isset($this->_advancedElements[$elementName])) {
697 unset($this->_advancedElements[$elementName]);
699 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
700 $this->setShowAdvanced();
701 $this->registerNoSubmitButton('mform_showadvanced');
703 $this->addElement('hidden', 'mform_showadvanced_last');
707 * Set whether to show advanced elements in the form on first displaying form. Default is not to
708 * display advanced elements in the form until 'Show Advanced' is pressed.
710 * You can get the last state of the form and possibly save it for this user by using
711 * value 'mform_showadvanced_last' in submitted data.
713 * @param boolean $showadvancedNow
715 function setShowAdvanced($showadvancedNow = null){
716 if ($showadvancedNow === null){
717 if ($this->_showAdvanced !== null){
718 return;
719 } else { //if setShowAdvanced is called without any preference
720 //make the default to not show advanced elements.
721 $showadvancedNow = get_user_preferences(
722 moodle_strtolower($this->_formName.'_showadvanced', 0));
725 //value of hidden element
726 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
727 //value of button
728 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
729 //toggle if button pressed or else stay the same
730 if ($hiddenLast == -1) {
731 $next = $showadvancedNow;
732 } elseif ($buttonPressed) { //toggle on button press
733 $next = !$hiddenLast;
734 } else {
735 $next = $hiddenLast;
737 $this->_showAdvanced = $next;
738 if ($showadvancedNow != $next){
739 set_user_preference($this->_formName.'_showadvanced', $next);
741 $this->setConstants(array('mform_showadvanced_last'=>$next));
743 function getShowAdvanced(){
744 return $this->_showAdvanced;
749 * Accepts a renderer
751 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
752 * @since 3.0
753 * @access public
754 * @return void
756 function accept(&$renderer)
758 if (method_exists($renderer, 'setAdvancedElements')){
759 //check for visible fieldsets where all elements are advanced
760 //and mark these headers as advanced as well.
761 //And mark all elements in a advanced header as advanced
762 $stopFields = $renderer->getStopFieldSetElements();
763 $lastHeader = null;
764 $lastHeaderAdvanced = false;
765 $anyAdvanced = false;
766 foreach (array_keys($this->_elements) as $elementIndex){
767 $element =& $this->_elements[$elementIndex];
768 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
769 if ($anyAdvanced && ($lastHeader!==null)){
770 $this->setAdvanced($lastHeader->getName());
772 $lastHeaderAdvanced = false;
773 } elseif ($lastHeaderAdvanced) {
774 $this->setAdvanced($element->getName());
776 if ($element->getType()=='header'){
777 $lastHeader =& $element;
778 $anyAdvanced = false;
779 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
780 } elseif (isset($this->_advancedElements[$element->getName()])){
781 $anyAdvanced = true;
784 $renderer->setAdvancedElements($this->_advancedElements);
787 parent::accept($renderer);
792 function closeHeaderBefore($elementName){
793 $renderer =& $this->defaultRenderer();
794 $renderer->addStopFieldsetElements($elementName);
798 * Should be used for all elements of a form except for select, radio and checkboxes which
799 * clean their own data.
801 * @param string $elementname
802 * @param integer $paramtype use the constants PARAM_*.
803 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
804 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
805 * It will strip all html tags. But will still let tags for multilang support
806 * through.
807 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
808 * html editor. Data from the editor is later cleaned before display using
809 * format_text() function. PARAM_RAW can also be used for data that is validated
810 * by some other way or printed by p() or s().
811 * * PARAM_INT should be used for integers.
812 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
813 * form actions.
815 function setType($elementname, $paramtype) {
816 $this->_types[$elementname] = $paramtype;
820 * See description of setType above. This can be used to set several types at once.
822 * @param array $paramtypes
824 function setTypes($paramtypes) {
825 $this->_types = $paramtypes + $this->_types;
828 function updateSubmission($submission, $files) {
829 $this->_flagSubmitted = false;
831 if (empty($submission)) {
832 $this->_submitValues = array();
833 } else {
834 foreach ($submission as $key=>$s) {
835 if (array_key_exists($key, $this->_types)) {
836 $submission[$key] = clean_param($s, $this->_types[$key]);
839 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
840 $this->_flagSubmitted = true;
843 if (empty($files)) {
844 $this->_submitFiles = array();
845 } else {
846 if (1 == get_magic_quotes_gpc()) {
847 foreach (array_keys($files) as $elname) {
848 // dangerous characters in filenames are cleaned later in upload_manager
849 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
852 $this->_submitFiles = $files;
853 $this->_flagSubmitted = true;
856 // need to tell all elements that they need to update their value attribute.
857 foreach (array_keys($this->_elements) as $key) {
858 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
862 function getReqHTML(){
863 return $this->_reqHTML;
866 function getAdvancedHTML(){
867 return $this->_advancedHTML;
871 * Initializes a default form value. Used to specify the default for a new entry where
872 * no data is loaded in using moodleform::set_data()
874 * @param string $elementname element name
875 * @param mixed $values values for that element name
876 * @param bool $slashed the default value is slashed
877 * @access public
878 * @return void
880 function setDefault($elementName, $defaultValue, $slashed=false){
881 $filter = $slashed ? 'stripslashes' : NULL;
882 $this->setDefaults(array($elementName=>$defaultValue), $filter);
883 } // end func setDefault
885 * Add an array of buttons to the form
886 * @param array $buttons An associative array representing help button to attach to
887 * to the form. keys of array correspond to names of elements in form.
889 * @access public
891 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
893 foreach ($buttons as $elementname => $button){
894 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
898 * Add a single button.
900 * @param string $elementname name of the element to add the item to
901 * @param array $button - arguments to pass to function $function
902 * @param boolean $suppresscheck - whether to throw an error if the element
903 * doesn't exist.
904 * @param string $function - function to generate html from the arguments in $button
906 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
907 if (array_key_exists($elementname, $this->_elementIndex)){
908 //_elements has a numeric index, this code accesses the elements by name
909 $element=&$this->_elements[$this->_elementIndex[$elementname]];
910 if (method_exists($element, 'setHelpButton')){
911 $element->setHelpButton($button, $function);
912 }else{
913 $a=new object();
914 $a->name=$element->getName();
915 $a->classname=get_class($element);
916 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
918 }elseif (!$suppresscheck){
919 print_error('nonexistentformelements', 'form', '', $elementname);
923 function exportValues($elementList= null, $addslashes=true){
924 $unfiltered = array();
925 if (null === $elementList) {
926 // iterate over all elements, calling their exportValue() methods
927 $emptyarray = array();
928 foreach (array_keys($this->_elements) as $key) {
929 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
930 $value = $this->_elements[$key]->exportValue($emptyarray, true);
931 } else {
932 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
935 if (is_array($value)) {
936 // This shit throws a bogus warning in PHP 4.3.x
937 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
940 } else {
941 if (!is_array($elementList)) {
942 $elementList = array_map('trim', explode(',', $elementList));
944 foreach ($elementList as $elementName) {
945 $value = $this->exportValue($elementName);
946 if (PEAR::isError($value)) {
947 return $value;
949 $unfiltered[$elementName] = $value;
953 if ($addslashes){
954 return $this->_recursiveFilter('addslashes', $unfiltered);
955 } else {
956 return $unfiltered;
960 * Adds a validation rule for the given field
962 * If the element is in fact a group, it will be considered as a whole.
963 * To validate grouped elements as separated entities,
964 * use addGroupRule instead of addRule.
966 * @param string $element Form element name
967 * @param string $message Message to display for invalid data
968 * @param string $type Rule type, use getRegisteredRules() to get types
969 * @param string $format (optional)Required for extra rule data
970 * @param string $validation (optional)Where to perform validation: "server", "client"
971 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
972 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
973 * @since 1.0
974 * @access public
975 * @throws HTML_QuickForm_Error
977 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
979 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
980 if ($validation == 'client') {
981 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
984 } // end func addRule
986 * Adds a validation rule for the given group of elements
988 * Only groups with a name can be assigned a validation rule
989 * Use addGroupRule when you need to validate elements inside the group.
990 * Use addRule if you need to validate the group as a whole. In this case,
991 * the same rule will be applied to all elements in the group.
992 * Use addRule if you need to validate the group against a function.
994 * @param string $group Form group name
995 * @param mixed $arg1 Array for multiple elements or error message string for one element
996 * @param string $type (optional)Rule type use getRegisteredRules() to get types
997 * @param string $format (optional)Required for extra rule data
998 * @param int $howmany (optional)How many valid elements should be in the group
999 * @param string $validation (optional)Where to perform validation: "server", "client"
1000 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1001 * @since 2.5
1002 * @access public
1003 * @throws HTML_QuickForm_Error
1005 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1007 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1008 if (is_array($arg1)) {
1009 foreach ($arg1 as $rules) {
1010 foreach ($rules as $rule) {
1011 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1013 if ('client' == $validation) {
1014 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1018 } elseif (is_string($arg1)) {
1020 if ($validation == 'client') {
1021 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1024 } // end func addGroupRule
1026 // }}}
1028 * Returns the client side validation script
1030 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1031 * and slightly modified to run rules per-element
1032 * Needed to override this because of an error with client side validation of grouped elements.
1034 * @access public
1035 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1037 function getValidationScript()
1039 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1040 return '';
1043 include_once('HTML/QuickForm/RuleRegistry.php');
1044 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1045 $test = array();
1046 $js_escape = array(
1047 "\r" => '\r',
1048 "\n" => '\n',
1049 "\t" => '\t',
1050 "'" => "\\'",
1051 '"' => '\"',
1052 '\\' => '\\\\'
1055 foreach ($this->_rules as $elementName => $rules) {
1056 foreach ($rules as $rule) {
1057 if ('client' == $rule['validation']) {
1058 unset($element); //TODO: find out how to properly initialize it
1060 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1061 $rule['message'] = strtr($rule['message'], $js_escape);
1063 if (isset($rule['group'])) {
1064 $group =& $this->getElement($rule['group']);
1065 // No JavaScript validation for frozen elements
1066 if ($group->isFrozen()) {
1067 continue 2;
1069 $elements =& $group->getElements();
1070 foreach (array_keys($elements) as $key) {
1071 if ($elementName == $group->getElementName($key)) {
1072 $element =& $elements[$key];
1073 break;
1076 } elseif ($dependent) {
1077 $element = array();
1078 $element[] =& $this->getElement($elementName);
1079 foreach ($rule['dependent'] as $elName) {
1080 $element[] =& $this->getElement($elName);
1082 } else {
1083 $element =& $this->getElement($elementName);
1085 // No JavaScript validation for frozen elements
1086 if (is_object($element) && $element->isFrozen()) {
1087 continue 2;
1088 } elseif (is_array($element)) {
1089 foreach (array_keys($element) as $key) {
1090 if ($element[$key]->isFrozen()) {
1091 continue 3;
1095 // Fix for bug displaying errors for elements in a group
1096 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1097 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1098 $test[$elementName][1]=$element;
1099 //end of fix
1104 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1105 // the form, and then that form field gets corrupted by the code that follows.
1106 unset($element);
1108 $js = '
1109 <script type="text/javascript">
1110 //<![CDATA[
1112 var skipClientValidation = false;
1114 function qf_errorHandler(element, _qfMsg) {
1115 div = element.parentNode;
1116 if (_qfMsg != \'\') {
1117 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1118 if (!errorSpan) {
1119 errorSpan = document.createElement("span");
1120 errorSpan.id = \'id_error_\'+element.name;
1121 errorSpan.className = "error";
1122 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1125 while (errorSpan.firstChild) {
1126 errorSpan.removeChild(errorSpan.firstChild);
1129 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1130 errorSpan.appendChild(document.createElement("br"));
1132 if (div.className.substr(div.className.length - 6, 6) != " error"
1133 && div.className != "error") {
1134 div.className += " error";
1137 return false;
1138 } else {
1139 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1140 if (errorSpan) {
1141 errorSpan.parentNode.removeChild(errorSpan);
1144 if (div.className.substr(div.className.length - 6, 6) == " error") {
1145 div.className = div.className.substr(0, div.className.length - 6);
1146 } else if (div.className == "error") {
1147 div.className = "";
1150 return true;
1153 $validateJS = '';
1154 foreach ($test as $elementName => $jsandelement) {
1155 // Fix for bug displaying errors for elements in a group
1156 //unset($element);
1157 list($jsArr,$element)=$jsandelement;
1158 //end of fix
1159 $js .= '
1160 function validate_' . $this->_formName . '_' . $elementName . '(element) {
1161 var value = \'\';
1162 var errFlag = new Array();
1163 var _qfGroups = {};
1164 var _qfMsg = \'\';
1165 var frm = element.parentNode;
1166 while (frm && frm.nodeName != "FORM") {
1167 frm = frm.parentNode;
1169 ' . join("\n", $jsArr) . '
1170 return qf_errorHandler(element, _qfMsg);
1173 $validateJS .= '
1174 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1175 if (!ret && !first_focus) {
1176 first_focus = true;
1177 frm.elements[\''.$elementName.'\'].focus();
1181 // Fix for bug displaying errors for elements in a group
1182 //unset($element);
1183 //$element =& $this->getElement($elementName);
1184 //end of fix
1185 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
1186 $onBlur = $element->getAttribute('onBlur');
1187 $onChange = $element->getAttribute('onChange');
1188 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1189 'onChange' => $onChange . $valFunc));
1191 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1192 $js .= '
1193 function validate_' . $this->_formName . '(frm) {
1194 if (skipClientValidation) {
1195 return true;
1197 var ret = true;
1199 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1200 var first_focus = false;
1201 ' . $validateJS . ';
1202 return ret;
1204 //]]>
1205 </script>';
1206 return $js;
1207 } // end func getValidationScript
1208 function _setDefaultRuleMessages(){
1209 foreach ($this->_rules as $field => $rulesarr){
1210 foreach ($rulesarr as $key => $rule){
1211 if ($rule['message']===null){
1212 $a=new object();
1213 $a->format=$rule['format'];
1214 $str=get_string('err_'.$rule['type'], 'form', $a);
1215 if (strpos($str, '[[')!==0){
1216 $this->_rules[$field][$key]['message']=$str;
1223 function getLockOptionEndScript(){
1225 $iname = $this->getAttribute('id').'items';
1226 $js = '<script type="text/javascript">'."\n";
1227 $js .= '//<![CDATA['."\n";
1228 $js .= "var $iname = Array();\n";
1230 foreach ($this->_dependencies as $dependentOn => $conditions){
1231 $js .= "{$iname}['$dependentOn'] = Array();\n";
1232 foreach ($conditions as $condition=>$values) {
1233 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1234 foreach ($values as $value=>$dependents) {
1235 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1236 $i = 0;
1237 foreach ($dependents as $dependent) {
1238 $elements = $this->_getElNamesRecursive($dependent);
1239 foreach($elements as $element) {
1240 if ($element == $dependentOn) {
1241 continue;
1243 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1244 $i++;
1250 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1251 $js .='//]]>'."\n";
1252 $js .='</script>'."\n";
1253 return $js;
1256 function _getElNamesRecursive($element, $group=null){
1257 if ($group==null){
1258 if (!$this->elementExists($element)) {
1259 return array();
1261 $el = $this->getElement($element);
1262 } else {
1263 $el = &$element;
1265 if (is_a($el, 'HTML_QuickForm_group')){
1266 $group = $el;
1267 $elsInGroup = $group->getElements();
1268 $elNames = array();
1269 foreach ($elsInGroup as $elInGroup){
1270 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1272 }else{
1273 if ($group != null){
1274 $elNames = array($group->getElementName($el->getName()));
1275 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1276 return null;
1277 } elseif (is_a($el, 'HTML_QuickForm_hidden')) {
1278 return null;
1279 } elseif (method_exists($el, 'getPrivateName')) {
1280 return array($el->getPrivateName());
1281 } else {
1282 $elNames = array($el->getName());
1285 return $elNames;
1289 * Adds a dependency for $elementName which will be disabled if $condition is met.
1290 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1291 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1292 * is checked. If $condition is something else then it is checked to see if the value
1293 * of the $dependentOn element is equal to $condition.
1295 * @param string $elementName the name of the element which will be disabled
1296 * @param string $dependentOn the name of the element whose state will be checked for
1297 * condition
1298 * @param string $condition the condition to check
1299 * @param mixed $value used in conjunction with condition.
1301 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1302 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1303 $this->_dependencies[$dependentOn] = array();
1305 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1306 $this->_dependencies[$dependentOn][$condition] = array();
1308 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1309 $this->_dependencies[$dependentOn][$condition][$value] = array();
1311 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1314 function registerNoSubmitButton($buttonname){
1315 $this->_noSubmitButtons[]=$buttonname;
1318 function isNoSubmitButton($buttonname){
1319 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1322 function _registerCancelButton($addfieldsname){
1323 $this->_cancelButtons[]=$addfieldsname;
1326 * Displays elements without HTML input tags.
1327 * This method is different to freeze() in that it makes sure no hidden
1328 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1329 * ignored.
1331 * This function also removes all previously defined rules.
1333 * @param mixed $elementList array or string of element(s) to be frozen
1334 * @since 1.0
1335 * @access public
1336 * @throws HTML_QuickForm_Error
1338 function hardFreeze($elementList=null)
1340 if (!isset($elementList)) {
1341 $this->_freezeAll = true;
1342 $elementList = array();
1343 } else {
1344 if (!is_array($elementList)) {
1345 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1347 $elementList = array_flip($elementList);
1350 foreach (array_keys($this->_elements) as $key) {
1351 $name = $this->_elements[$key]->getName();
1352 if ($this->_freezeAll || isset($elementList[$name])) {
1353 $this->_elements[$key]->freeze();
1354 $this->_elements[$key]->setPersistantFreeze(false);
1355 unset($elementList[$name]);
1357 // remove all rules
1358 $this->_rules[$name] = array();
1359 // if field is required, remove the rule
1360 $unset = array_search($name, $this->_required);
1361 if ($unset !== false) {
1362 unset($this->_required[$unset]);
1367 if (!empty($elementList)) {
1368 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);
1370 return true;
1373 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1375 * This function also removes all previously defined rules of elements it freezes.
1377 * @param array $elementList array or string of element(s) not to be frozen
1378 * @since 1.0
1379 * @access public
1380 * @throws HTML_QuickForm_Error
1382 function hardFreezeAllVisibleExcept($elementList)
1384 $elementList = array_flip($elementList);
1385 foreach (array_keys($this->_elements) as $key) {
1386 $name = $this->_elements[$key]->getName();
1387 $type = $this->_elements[$key]->getType();
1389 if ($type == 'hidden'){
1390 // leave hidden types as they are
1391 } elseif (!isset($elementList[$name])) {
1392 $this->_elements[$key]->freeze();
1393 $this->_elements[$key]->setPersistantFreeze(false);
1395 // remove all rules
1396 $this->_rules[$name] = array();
1397 // if field is required, remove the rule
1398 $unset = array_search($name, $this->_required);
1399 if ($unset !== false) {
1400 unset($this->_required[$unset]);
1404 return true;
1407 * Tells whether the form was already submitted
1409 * This is useful since the _submitFiles and _submitValues arrays
1410 * may be completely empty after the trackSubmit value is removed.
1412 * @access public
1413 * @return bool
1415 function isSubmitted()
1417 return parent::isSubmitted() && (!$this->isFrozen());
1423 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1424 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1426 * Stylesheet is part of standard theme and should be automatically included.
1428 * @author Jamie Pratt <me@jamiep.org>
1429 * @license gpl license
1431 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1434 * Element template array
1435 * @var array
1436 * @access private
1438 var $_elementTemplates;
1440 * Template used when opening a hidden fieldset
1441 * (i.e. a fieldset that is opened when there is no header element)
1442 * @var string
1443 * @access private
1445 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\">";
1447 * Header Template string
1448 * @var string
1449 * @access private
1451 var $_headerTemplate =
1452 "\n\t\t<legend>{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div>\n\t\t";
1455 * Template used when opening a fieldset
1456 * @var string
1457 * @access private
1459 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1462 * Template used when closing a fieldset
1463 * @var string
1464 * @access private
1466 var $_closeFieldsetTemplate = "\n\t\t</fieldset>";
1469 * Required Note template string
1470 * @var string
1471 * @access private
1473 var $_requiredNoteTemplate =
1474 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1476 var $_advancedElements = array();
1479 * Whether to display advanced elements (on page load)
1481 * @var integer 1 means show 0 means hide
1483 var $_showAdvanced;
1485 function MoodleQuickForm_Renderer(){
1486 // switch next two lines for ol li containers for form items.
1487 // $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>');
1488 $this->_elementTemplates = array(
1489 'default'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req} <!-- END required -->{advancedimg}</label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
1491 '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}</div>{help}</div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
1493 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req} <!-- END required -->{advancedimg}</div>{help}</div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}&nbsp;</div></div>',
1495 'nodisplay'=>'');
1497 parent::HTML_QuickForm_Renderer_Tableless();
1500 function setAdvancedElements($elements){
1501 $this->_advancedElements = $elements;
1505 * What to do when starting the form
1507 * @param MoodleQuickForm $form
1509 function startForm(&$form){
1510 $this->_reqHTML = $form->getReqHTML();
1511 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1512 $this->_advancedHTML = $form->getAdvancedHTML();
1513 $this->_showAdvanced = $form->getShowAdvanced();
1514 parent::startForm($form);
1515 if ($form->isFrozen()){
1516 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
1517 } else {
1518 $this->_hiddenHtml .= $form->_pageparams;
1524 function startGroup(&$group, $required, $error){
1525 if (method_exists($group, 'getElementTemplateType')){
1526 $html = $this->_elementTemplates[$group->getElementTemplateType()];
1527 }else{
1528 $html = $this->_elementTemplates['default'];
1531 if ($this->_showAdvanced){
1532 $advclass = ' advanced';
1533 } else {
1534 $advclass = ' advanced hide';
1536 if (isset($this->_advancedElements[$group->getName()])){
1537 $html =str_replace(' {advanced}', $advclass, $html);
1538 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1539 } else {
1540 $html =str_replace(' {advanced}', '', $html);
1541 $html =str_replace('{advancedimg}', '', $html);
1543 if (method_exists($group, 'getHelpButton')){
1544 $html =str_replace('{help}', $group->getHelpButton(), $html);
1545 }else{
1546 $html =str_replace('{help}', '', $html);
1548 $html =str_replace('{name}', $group->getName(), $html);
1549 $html =str_replace('{type}', 'fgroup', $html);
1551 $this->_templates[$group->getName()]=$html;
1552 // Fix for bug in tableless quickforms that didn't allow you to stop a
1553 // fieldset before a group of elements.
1554 // if the element name indicates the end of a fieldset, close the fieldset
1555 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1556 && $this->_fieldsetsOpen > 0
1558 $this->_html .= $this->_closeFieldsetTemplate;
1559 $this->_fieldsetsOpen--;
1561 parent::startGroup($group, $required, $error);
1564 function renderElement(&$element, $required, $error){
1565 //manipulate id of all elements before rendering
1566 if (!is_null($element->getAttribute('id'))) {
1567 $id = $element->getAttribute('id');
1568 } else {
1569 $id = $element->getName();
1571 //strip qf_ prefix and replace '[' with '_' and strip ']'
1572 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1573 if (strpos($id, 'id_') !== 0){
1574 $element->updateAttributes(array('id'=>'id_'.$id));
1577 //adding stuff to place holders in template
1578 if (method_exists($element, 'getElementTemplateType')){
1579 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1580 }else{
1581 $html = $this->_elementTemplates['default'];
1583 if ($this->_showAdvanced){
1584 $advclass = ' advanced';
1585 } else {
1586 $advclass = ' advanced hide';
1588 if (isset($this->_advancedElements[$element->getName()])){
1589 $html =str_replace(' {advanced}', $advclass, $html);
1590 } else {
1591 $html =str_replace(' {advanced}', '', $html);
1593 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1594 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1595 } else {
1596 $html =str_replace('{advancedimg}', '', $html);
1598 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1599 $html =str_replace('{name}', $element->getName(), $html);
1600 if (method_exists($element, 'getHelpButton')){
1601 $html = str_replace('{help}', $element->getHelpButton(), $html);
1602 }else{
1603 $html = str_replace('{help}', '', $html);
1607 $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');