Bumping version for 1.8.9 release. Thinking we might have to go to x.x.10 for the...
[moodle.git] / lib / formslib.php
blob1f7f50fa9285103ce1932911b9608aaa44661de8
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; //
80 /**
81 * The constructor function calls the abstract function definition() and it will then
82 * process and clean and attempt to validate incoming data.
84 * It will call your custom validate method to validate data and will also check any rules
85 * you have specified in definition using addRule
87 * The name of the form (id attribute of the form) is automatically generated depending on
88 * the name you gave the class extending moodleform. You should call your class something
89 * like
91 * @param string $action the action attribute for the form. If empty defaults to auto detect the
92 * current url.
93 * @param array $customdata if your form defintion method needs access to data such as $course
94 * $cm, etc. to construct the form definition then pass it in this array. You can
95 * use globals for somethings.
96 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
97 * be merged and used as incoming data to the form.
98 * @param string $target target frame for form submission. You will rarely use this. Don't use
99 * it if you don't need to as the target attribute is deprecated in xhtml
100 * strict.
101 * @param mixed $attributes you can pass a string of html attributes here or an array.
102 * @return moodleform
104 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null) {
105 if (empty($action)){
106 $action = strip_querystring(qualified_me());
109 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
110 $this->_customdata = $customdata;
111 $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
112 $this->set_upload_manager(new upload_manager());
114 $this->definition();
116 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
117 $this->_form->setDefault('sesskey', sesskey());
118 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
119 $this->_form->setDefault('_qf__'.$this->_formname, 1);
120 $this->_form->_setDefaultRuleMessages();
122 // we have to know all input types before processing submission ;-)
123 $this->_process_submission($method);
125 // update form definition based on final data
126 $this->definition_after_data();
130 * To autofocus on first form element or first element with error.
132 * @param string $name if this is set then the focus is forced to a field with this name
134 * @return string javascript to select form element with first error or
135 * first element if no errors. Use this as a parameter
136 * when calling print_header
138 function focus($name=NULL){
139 $form =& $this->_form;
140 $elkeys=array_keys($form->_elementIndex);
141 if (isset($form->_errors) && 0 != count($form->_errors)){
142 $errorkeys = array_keys($form->_errors);
143 $elkeys = array_intersect($elkeys, $errorkeys);
145 $names=null;
146 while (!$names){
147 $el = array_shift($elkeys);
148 $names = $form->_getElNamesRecursive($el);
150 if (empty($name)) {
151 $name=array_shift($names);
153 $focus='forms[\''.$this->_form->getAttribute('id').'\'].elements[\''.$name.'\']';
154 return $focus;
158 * Internal method. Alters submitted data to be suitable for quickforms processing.
159 * Must be called when the form is fully set up.
161 function _process_submission($method) {
162 $submission = array();
163 if ($method == 'post') {
164 if (!empty($_POST)) {
165 $submission = $_POST;
167 } else {
168 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
171 // following trick is needed to enable proper sesskey checks when using GET forms
172 // the _qf__.$this->_formname serves as a marker that form was actually submitted
173 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
174 if (!confirm_sesskey()) {
175 error('Incorrect sesskey submitted, form not accepted!');
177 $files = $_FILES;
178 } else {
179 $submission = array();
180 $files = array();
183 $this->_form->updateSubmission($submission, $files);
187 * Internal method. Validates all uploaded files.
189 function _validate_files() {
190 if (empty($_FILES)) {
191 // we do not need to do any checks because no files were submitted
192 // TODO: find out why server side required rule does not work for uploaded files;
193 // testing is easily done by always returning true from this function and adding
194 // $mform->addRule('soubor', get_string('required'), 'required', null, 'server');
195 // and submitting form without selected file
196 return true;
198 $errors = array();
199 $mform =& $this->_form;
201 // check the files
202 $status = $this->_upload_manager->preprocess_files();
204 // now check that we really want each file
205 foreach ($_FILES as $elname=>$file) {
206 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
207 $required = $mform->isElementRequired($elname);
208 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
209 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
210 // file not uploaded and not required - ignore it
211 continue;
213 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
215 } else {
216 error('Incorrect upload attempt!');
220 // return errors if found
221 if ($status and 0 == count($errors)){
222 return true;
223 } else {
224 return $errors;
229 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
230 * form definition (new entry form); this function is used to load in data where values
231 * already exist and data is being edited (edit entry form).
233 * @param mixed $default_values object or array of default values
234 * @param bool $slased true if magic quotes applied to data values
236 function set_data($default_values, $slashed=false) {
237 if (is_object($default_values)) {
238 $default_values = (array)$default_values;
240 $filter = $slashed ? 'stripslashes' : NULL;
241 $this->_form->setDefaults($default_values, $filter);
242 //update form definition when data changed
243 $this->definition_after_data();
247 * Set custom upload manager.
248 * Must be used BEFORE creating of file element!
250 * @param object $um - custom upload manager
252 function set_upload_manager($um=false) {
253 if ($um === false) {
254 $um = new upload_manager();
256 $this->_upload_manager = $um;
258 $this->_form->setMaxFileSize($um->config->maxbytes);
262 * Check that form was submitted. Does not check validity of submitted data.
264 * @return bool true if form properly submitted
266 function is_submitted() {
267 return $this->_form->isSubmitted();
270 function no_submit_button_pressed(){
271 static $nosubmit = null; // one check is enough
272 if (!is_null($nosubmit)){
273 return $nosubmit;
275 $mform =& $this->_form;
276 $nosubmit = false;
277 if (!$this->is_submitted()){
278 return false;
280 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
281 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
282 $nosubmit = true;
283 break;
286 return $nosubmit;
291 * Check that form data is valid.
293 * @return bool true if form data valid
295 function is_validated() {
296 static $validated = null; // one validation is enough
297 $mform =& $this->_form;
299 if ($this->no_submit_button_pressed()){
300 return false;
301 } elseif ($validated === null) {
302 $internal_val = $mform->validate();
303 $moodle_val = $this->validation($mform->exportValues(null, true));
304 if ($moodle_val !== true) {
305 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
306 foreach ($moodle_val as $element=>$msg) {
307 $mform->setElementError($element, $msg);
309 $moodle_val = false;
310 } else {
311 $moodle_val = true;
314 $file_val = $this->_validate_files();
315 if ($file_val !== true) {
316 if (!empty($file_val)) {
317 foreach ($file_val as $element=>$msg) {
318 $mform->setElementError($element, $msg);
321 $file_val = false;
323 $validated = ($internal_val and $moodle_val and $file_val);
325 return $validated;
329 * Return true if a cancel button has been pressed resulting in the form being submitted.
331 * @return boolean true if a cancel button has been pressed
333 function is_cancelled(){
334 $mform =& $this->_form;
335 if ($mform->isSubmitted()){
336 foreach ($mform->_cancelButtons as $cancelbutton){
337 if (optional_param($cancelbutton, 0, PARAM_RAW)){
338 return true;
342 return false;
346 * Return submitted data if properly submitted or returns NULL if validation fails or
347 * if there is no submitted data.
349 * @param bool $slashed true means return data with addslashes applied
350 * @return object submitted data; NULL if not valid or not submitted
352 function get_data($slashed=true) {
353 $mform =& $this->_form;
355 if ($this->is_submitted() and $this->is_validated()) {
356 $data = $mform->exportValues(null, $slashed);
357 unset($data['sesskey']); // we do not need to return sesskey
358 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
359 if (empty($data)) {
360 return NULL;
361 } else {
362 return (object)$data;
364 } else {
365 return NULL;
370 * Save verified uploaded files into directory. Upload process can be customised from definition()
371 * method by creating instance of upload manager and storing it in $this->_upload_form
373 * @param string $destination where to store uploaded files
374 * @return bool success
376 function save_files($destination) {
377 if ($this->is_submitted() and $this->is_validated()) {
378 return $this->_upload_manager->save_files($destination);
380 return false;
384 * If we're only handling one file (if inputname was given in the constructor)
385 * this will return the (possibly changed) filename of the file.
386 * @return mixed false in case of failure, string if ok
388 function get_new_filename() {
389 return $this->_upload_manager->get_new_filename();
393 * Print html form.
395 function display() {
396 $this->_form->display();
400 * Abstract method - always override!
402 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
404 function definition() {
405 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
409 * Dummy stub method - override if you need to setup the form depending on current
410 * values. This method is called after definition(), data submission and set_data().
411 * All form setup that is dependent on form values should go in here.
413 function definition_after_data(){
417 * Dummy stub method - override if you needed to perform some extra validation.
418 * If there are errors return array of errors ("fieldname"=>"error message"),
419 * otherwise true if ok.
421 * @param array $data array of ("fieldname"=>value) of submitted data
422 * @return bool array of errors or true if ok
424 function validation($data) {
425 return true;
433 * Method to add a repeating group of elements to a form.
435 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
436 * @param integer $repeats no of times to repeat elements initially
437 * @param array $options Array of options to apply to elements. Array keys are element names.
438 * This is an array of arrays. The second sets of keys are the option types
439 * for the elements :
440 * 'default' - default value is value
441 * 'type' - PARAM_* constant is value
442 * 'helpbutton' - helpbutton params array is value
443 * 'disabledif' - last three moodleform::disabledIf()
444 * params are value as an array
445 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
446 * @param string $addfieldsname name for button to add more fields
447 * @param int $addfieldsno how many fields to add at a time
448 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
449 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
450 * @return int no of repeats of element in this page
452 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
453 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
454 if ($addstring===null){
455 $addstring = get_string('addfields', 'form', $addfieldsno);
456 } else {
457 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
459 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
460 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
461 if (!empty($addfields)){
462 $repeats += $addfieldsno;
464 $mform =& $this->_form;
465 $mform->registerNoSubmitButton($addfieldsname);
466 $mform->addElement('hidden', $repeathiddenname, $repeats);
467 //value not to be overridden by submitted value
468 $mform->setConstants(array($repeathiddenname=>$repeats));
469 for ($i=0; $i<$repeats; $i++) {
470 foreach ($elementobjs as $elementobj){
471 $elementclone = fullclone($elementobj);
472 $name = $elementclone->getName();
473 if (!empty($name)){
474 $elementclone->setName($name."[$i]");
476 if (is_a($elementclone, 'HTML_QuickForm_header')){
477 $value=$elementclone->_text;
478 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
480 } else {
481 $value=$elementclone->getLabel();
482 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
486 $mform->addElement($elementclone);
489 for ($i=0; $i<$repeats; $i++) {
490 foreach ($options as $elementname => $elementoptions){
491 $pos=strpos($elementname, '[');
492 if ($pos!==FALSE){
493 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
494 $realelementname .= substr($elementname, $pos+1);
495 }else {
496 $realelementname = $elementname."[$i]";
498 foreach ($elementoptions as $option => $params){
500 switch ($option){
501 case 'default' :
502 $mform->setDefault($realelementname, $params);
503 break;
504 case 'helpbutton' :
505 $mform->setHelpButton($realelementname, $params);
506 break;
507 case 'disabledif' :
508 $params = array_merge(array($realelementname), $params);
509 call_user_func_array(array(&$mform, 'disabledIf'), $params);
510 break;
511 case 'rule' :
512 if (is_string($params)){
513 $params = array(null, $params, null, 'client');
515 $params = array_merge(array($realelementname), $params);
516 call_user_func_array(array(&$mform, 'addRule'), $params);
517 break;
523 $mform->addElement('submit', $addfieldsname, $addstring);
525 if (!$addbuttoninside) {
526 $mform->closeHeaderBefore($addfieldsname);
529 return $repeats;
532 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
533 * if you don't want a cancel button in your form. If you have a cancel button make sure you
534 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
535 * get data with get_data().
537 * @param boolean $cancel whether to show cancel button, default true
538 * @param boolean $revert whether to show revert button, default true
539 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
541 function add_action_buttons($cancel = true, $submitlabel=null){
542 if (is_null($submitlabel)){
543 $submitlabel = get_string('savechanges');
545 $mform =& $this->_form;
546 if ($cancel){
547 //when two elements we need a group
548 $buttonarray=array();
549 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
550 $buttonarray[] = &$mform->createElement('cancel');
551 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
552 $mform->closeHeaderBefore('buttonar');
553 } else {
554 //no group needed
555 $mform->addElement('submit', 'submitbutton', $submitlabel);
556 $mform->closeHeaderBefore('submitbutton');
562 * You never extend this class directly. The class methods of this class are available from
563 * the private $this->_form property on moodleform and it's children. You generally only
564 * call methods on this class from within abstract methods that you override on moodleform such
565 * as definition and definition_after_data
568 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
569 var $_types = array();
570 var $_dependencies = array();
572 * Array of buttons that if pressed do not result in the processing of the form.
574 * @var array
576 var $_noSubmitButtons=array();
578 * Array of buttons that if pressed do not result in the processing of the form.
580 * @var array
582 var $_cancelButtons=array();
585 * Array whose keys are element names. If the key exists this is a advanced element
587 * @var array
589 var $_advancedElements = array();
592 * Whether to display advanced elements (on page load)
594 * @var boolean
596 var $_showAdvanced = null;
599 * The form name is derrived from the class name of the wrapper minus the trailing form
600 * It is a name with words joined by underscores whereas the id attribute is words joined by
601 * underscores.
603 * @var unknown_type
605 var $_formName = '';
608 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
609 * @param string $formName Form's name.
610 * @param string $method (optional)Form's method defaults to 'POST'
611 * @param string $action (optional)Form's action
612 * @param string $target (optional)Form's target defaults to none
613 * @param mixed $attributes (optional)Extra attributes for <form> tag
614 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
615 * @access public
617 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
618 global $CFG;
620 static $formcounter = 1;
622 HTML_Common::HTML_Common($attributes);
623 $target = empty($target) ? array() : array('target' => $target);
624 $this->_formName = $formName;
625 //no 'name' atttribute for form in xhtml strict :
626 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
627 $formcounter++;
628 $this->updateAttributes($attributes);
630 //this is custom stuff for Moodle :
631 $oldclass= $this->getAttribute('class');
632 if (!empty($oldclass)){
633 $this->updateAttributes(array('class'=>$oldclass.' mform'));
634 }else {
635 $this->updateAttributes(array('class'=>'mform'));
637 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
638 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
639 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
640 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
644 * Use this method to indicate an element in a form is an advanced field. If items in a form
645 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
646 * form so the user can decide whether to display advanced form controls.
648 * If you set a header element to advanced then all elements it contains will also be set as advanced.
650 * @param string $elementName group or element name (not the element name of something inside a group).
651 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
653 function setAdvanced($elementName, $advanced=true){
654 if ($advanced){
655 $this->_advancedElements[$elementName]='';
656 } elseif (isset($this->_advancedElements[$elementName])) {
657 unset($this->_advancedElements[$elementName]);
659 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
660 $this->setShowAdvanced();
661 $this->registerNoSubmitButton('mform_showadvanced');
663 $this->addElement('hidden', 'mform_showadvanced_last');
667 * Set whether to show advanced elements in the form on first displaying form. Default is not to
668 * display advanced elements in the form until 'Show Advanced' is pressed.
670 * You can get the last state of the form and possibly save it for this user by using
671 * value 'mform_showadvanced_last' in submitted data.
673 * @param boolean $showadvancedNow
675 function setShowAdvanced($showadvancedNow = null){
676 if ($showadvancedNow === null){
677 if ($this->_showAdvanced !== null){
678 return;
679 } else { //if setShowAdvanced is called without any preference
680 //make the default to not show advanced elements.
681 $showadvancedNow = get_user_preferences(
682 moodle_strtolower($this->_formName.'_showadvanced', 0));
685 //value of hidden element
686 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
687 //value of button
688 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
689 //toggle if button pressed or else stay the same
690 if ($hiddenLast == -1) {
691 $next = $showadvancedNow;
692 } elseif ($buttonPressed) { //toggle on button press
693 $next = !$hiddenLast;
694 } else {
695 $next = $hiddenLast;
697 $this->_showAdvanced = $next;
698 if ($showadvancedNow != $next){
699 set_user_preference($this->_formName.'_showadvanced', $next);
701 $this->setConstants(array('mform_showadvanced_last'=>$next));
703 function getShowAdvanced(){
704 return $this->_showAdvanced;
709 * Accepts a renderer
711 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
712 * @since 3.0
713 * @access public
714 * @return void
716 function accept(&$renderer)
718 if (method_exists($renderer, 'setAdvancedElements')){
719 //check for visible fieldsets where all elements are advanced
720 //and mark these headers as advanced as well.
721 //And mark all elements in a advanced header as advanced
722 $stopFields = $renderer->getStopFieldSetElements();
723 $lastHeader = null;
724 $lastHeaderAdvanced = false;
725 $anyAdvanced = false;
726 foreach (array_keys($this->_elements) as $elementIndex){
727 $element =& $this->_elements[$elementIndex];
728 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
729 if ($anyAdvanced && ($lastHeader!==null)){
730 $this->setAdvanced($lastHeader->getName());
732 $lastHeaderAdvanced = false;
733 } elseif ($lastHeaderAdvanced) {
734 $this->setAdvanced($element->getName());
736 if ($element->getType()=='header'){
737 $lastHeader =& $element;
738 $anyAdvanced = false;
739 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
740 } elseif (isset($this->_advancedElements[$element->getName()])){
741 $anyAdvanced = true;
744 $renderer->setAdvancedElements($this->_advancedElements);
747 parent::accept($renderer);
752 function closeHeaderBefore($elementName){
753 $renderer =& $this->defaultRenderer();
754 $renderer->addStopFieldsetElements($elementName);
758 * Should be used for all elements of a form except for select, radio and checkboxes which
759 * clean their own data.
761 * @param string $elementname
762 * @param integer $paramtype use the constants PARAM_*.
763 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
764 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
765 * It will strip all html tags. But will still let tags for multilang support
766 * through.
767 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
768 * html editor. Data from the editor is later cleaned before display using
769 * format_text() function. PARAM_RAW can also be used for data that is validated
770 * by some other way or printed by p() or s().
771 * * PARAM_INT should be used for integers.
772 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
773 * form actions.
775 function setType($elementname, $paramtype) {
776 $this->_types[$elementname] = $paramtype;
780 * See description of setType above. This can be used to set several types at once.
782 * @param array $paramtypes
784 function setTypes($paramtypes) {
785 $this->_types = $paramtypes + $this->_types;
788 function updateSubmission($submission, $files) {
789 $this->_flagSubmitted = false;
791 if (empty($submission)) {
792 $this->_submitValues = array();
793 } else {
794 foreach ($submission as $key=>$s) {
795 if (array_key_exists($key, $this->_types)) {
796 $submission[$key] = clean_param($s, $this->_types[$key]);
799 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
800 $this->_flagSubmitted = true;
803 if (empty($files)) {
804 $this->_submitFiles = array();
805 } else {
806 if (1 == get_magic_quotes_gpc()) {
807 foreach (array_keys($files) as $elname) {
808 // dangerous characters in filenames are cleaned later in upload_manager
809 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
812 $this->_submitFiles = $files;
813 $this->_flagSubmitted = true;
816 // need to tell all elements that they need to update their value attribute.
817 foreach (array_keys($this->_elements) as $key) {
818 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
822 function getReqHTML(){
823 return $this->_reqHTML;
826 function getAdvancedHTML(){
827 return $this->_advancedHTML;
831 * Initializes a default form value. Used to specify the default for a new entry where
832 * no data is loaded in using moodleform::set_data()
834 * @param string $elementname element name
835 * @param mixed $values values for that element name
836 * @param bool $slashed the default value is slashed
837 * @access public
838 * @return void
840 function setDefault($elementName, $defaultValue, $slashed=false){
841 $filter = $slashed ? 'stripslashes' : NULL;
842 $this->setDefaults(array($elementName=>$defaultValue), $filter);
843 } // end func setDefault
845 * Add an array of buttons to the form
846 * @param array $buttons An associative array representing help button to attach to
847 * to the form. keys of array correspond to names of elements in form.
849 * @access public
851 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
853 foreach ($buttons as $elementname => $button){
854 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
858 * Add a single button.
860 * @param string $elementname name of the element to add the item to
861 * @param array $button - arguments to pass to function $function
862 * @param boolean $suppresscheck - whether to throw an error if the element
863 * doesn't exist.
864 * @param string $function - function to generate html from the arguments in $button
866 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
867 if (array_key_exists($elementname, $this->_elementIndex)){
868 //_elements has a numeric index, this code accesses the elements by name
869 $element=&$this->_elements[$this->_elementIndex[$elementname]];
870 if (method_exists($element, 'setHelpButton')){
871 $element->setHelpButton($button, $function);
872 }else{
873 $a=new object();
874 $a->name=$element->getName();
875 $a->classname=get_class($element);
876 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
878 }elseif (!$suppresscheck){
879 print_error('nonexistentformelements', 'form', '', $elementname);
884 * Set constant value not overriden by _POST or _GET
885 * note: this does not work for complex names with [] :-(
886 * @param string $elname name of element
887 * @param mixed $value
888 * @return void
890 function setConstant($elname, $value) {
891 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
892 $element =& $this->getElement($elname);
893 $element->onQuickFormEvent('updateValue', null, $this);
896 function exportValues($elementList= null, $addslashes=true){
897 $unfiltered = array();
898 if (null === $elementList) {
899 // iterate over all elements, calling their exportValue() methods
900 $emptyarray = array();
901 foreach (array_keys($this->_elements) as $key) {
902 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
903 $value = $this->_elements[$key]->exportValue($emptyarray, true);
904 } else {
905 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
908 if (is_array($value)) {
909 // This shit throws a bogus warning in PHP 4.3.x
910 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
913 } else {
914 if (!is_array($elementList)) {
915 $elementList = array_map('trim', explode(',', $elementList));
917 foreach ($elementList as $elementName) {
918 $value = $this->exportValue($elementName);
919 if (PEAR::isError($value)) {
920 return $value;
922 $unfiltered[$elementName] = $value;
926 if ($addslashes){
927 return $this->_recursiveFilter('addslashes', $unfiltered);
928 } else {
929 return $unfiltered;
933 * Adds a validation rule for the given field
935 * If the element is in fact a group, it will be considered as a whole.
936 * To validate grouped elements as separated entities,
937 * use addGroupRule instead of addRule.
939 * @param string $element Form element name
940 * @param string $message Message to display for invalid data
941 * @param string $type Rule type, use getRegisteredRules() to get types
942 * @param string $format (optional)Required for extra rule data
943 * @param string $validation (optional)Where to perform validation: "server", "client"
944 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
945 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
946 * @since 1.0
947 * @access public
948 * @throws HTML_QuickForm_Error
950 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
952 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
953 if ($validation == 'client') {
954 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
957 } // end func addRule
959 * Adds a validation rule for the given group of elements
961 * Only groups with a name can be assigned a validation rule
962 * Use addGroupRule when you need to validate elements inside the group.
963 * Use addRule if you need to validate the group as a whole. In this case,
964 * the same rule will be applied to all elements in the group.
965 * Use addRule if you need to validate the group against a function.
967 * @param string $group Form group name
968 * @param mixed $arg1 Array for multiple elements or error message string for one element
969 * @param string $type (optional)Rule type use getRegisteredRules() to get types
970 * @param string $format (optional)Required for extra rule data
971 * @param int $howmany (optional)How many valid elements should be in the group
972 * @param string $validation (optional)Where to perform validation: "server", "client"
973 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
974 * @since 2.5
975 * @access public
976 * @throws HTML_QuickForm_Error
978 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
980 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
981 if (is_array($arg1)) {
982 foreach ($arg1 as $rules) {
983 foreach ($rules as $rule) {
984 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
986 if ('client' == $validation) {
987 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
991 } elseif (is_string($arg1)) {
993 if ($validation == 'client') {
994 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
997 } // end func addGroupRule
999 // }}}
1001 * Returns the client side validation script
1003 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1004 * and slightly modified to run rules per-element
1005 * Needed to override this because of an error with client side validation of grouped elements.
1007 * @access public
1008 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1010 function getValidationScript()
1012 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1013 return '';
1016 include_once('HTML/QuickForm/RuleRegistry.php');
1017 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1018 $test = array();
1019 $js_escape = array(
1020 "\r" => '\r',
1021 "\n" => '\n',
1022 "\t" => '\t',
1023 "'" => "\\'",
1024 '"' => '\"',
1025 '\\' => '\\\\'
1028 foreach ($this->_rules as $elementName => $rules) {
1029 foreach ($rules as $rule) {
1030 if ('client' == $rule['validation']) {
1031 unset($element); //TODO: find out how to properly initialize it
1033 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1034 $rule['message'] = strtr($rule['message'], $js_escape);
1036 if (isset($rule['group'])) {
1037 $group =& $this->getElement($rule['group']);
1038 // No JavaScript validation for frozen elements
1039 if ($group->isFrozen()) {
1040 continue 2;
1042 $elements =& $group->getElements();
1043 foreach (array_keys($elements) as $key) {
1044 if ($elementName == $group->getElementName($key)) {
1045 $element =& $elements[$key];
1046 break;
1049 } elseif ($dependent) {
1050 $element = array();
1051 $element[] =& $this->getElement($elementName);
1052 foreach ($rule['dependent'] as $elName) {
1053 $element[] =& $this->getElement($elName);
1055 } else {
1056 $element =& $this->getElement($elementName);
1058 // No JavaScript validation for frozen elements
1059 if (is_object($element) && $element->isFrozen()) {
1060 continue 2;
1061 } elseif (is_array($element)) {
1062 foreach (array_keys($element) as $key) {
1063 if ($element[$key]->isFrozen()) {
1064 continue 3;
1068 // Fix for bug displaying errors for elements in a group
1069 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1070 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1071 $test[$elementName][1]=$element;
1072 //end of fix
1077 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1078 // the form, and then that form field gets corrupted by the code that follows.
1079 unset($element);
1081 $js = '
1082 <script type="text/javascript">
1083 //<![CDATA[
1085 var skipClientValidation = false;
1087 function qf_errorHandler(element, _qfMsg) {
1088 div = element.parentNode;
1089 if (_qfMsg != \'\') {
1090 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1091 if (!errorSpan) {
1092 errorSpan = document.createElement("span");
1093 errorSpan.id = \'id_error_\'+element.name;
1094 errorSpan.className = "error";
1095 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1098 while (errorSpan.firstChild) {
1099 errorSpan.removeChild(errorSpan.firstChild);
1102 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1103 errorSpan.appendChild(document.createElement("br"));
1105 if (div.className.substr(div.className.length - 6, 6) != " error"
1106 && div.className != "error") {
1107 div.className += " error";
1110 return false;
1111 } else {
1112 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1113 if (errorSpan) {
1114 errorSpan.parentNode.removeChild(errorSpan);
1117 if (div.className.substr(div.className.length - 6, 6) == " error") {
1118 div.className = div.className.substr(0, div.className.length - 6);
1119 } else if (div.className == "error") {
1120 div.className = "";
1123 return true;
1126 $validateJS = '';
1127 foreach ($test as $elementName => $jsandelement) {
1128 // Fix for bug displaying errors for elements in a group
1129 //unset($element);
1130 list($jsArr,$element)=$jsandelement;
1131 //end of fix
1132 $js .= '
1133 function validate_' . $this->_formName . '_' . $elementName . '(element) {
1134 var value = \'\';
1135 var errFlag = new Array();
1136 var _qfGroups = {};
1137 var _qfMsg = \'\';
1138 var frm = element.parentNode;
1139 while (frm && frm.nodeName != "FORM") {
1140 frm = frm.parentNode;
1142 ' . join("\n", $jsArr) . '
1143 return qf_errorHandler(element, _qfMsg);
1146 $validateJS .= '
1147 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1148 if (!ret && !first_focus) {
1149 first_focus = true;
1150 frm.elements[\''.$elementName.'\'].focus();
1154 // Fix for bug displaying errors for elements in a group
1155 //unset($element);
1156 //$element =& $this->getElement($elementName);
1157 //end of fix
1158 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
1159 $onBlur = $element->getAttribute('onBlur');
1160 $onChange = $element->getAttribute('onChange');
1161 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1162 'onChange' => $onChange . $valFunc));
1164 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1165 $js .= '
1166 function validate_' . $this->_formName . '(frm) {
1167 if (skipClientValidation) {
1168 return true;
1170 var ret = true;
1172 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1173 var first_focus = false;
1174 ' . $validateJS . ';
1175 return ret;
1177 //]]>
1178 </script>';
1179 return $js;
1180 } // end func getValidationScript
1181 function _setDefaultRuleMessages(){
1182 foreach ($this->_rules as $field => $rulesarr){
1183 foreach ($rulesarr as $key => $rule){
1184 if ($rule['message']===null){
1185 $a=new object();
1186 $a->format=$rule['format'];
1187 $str=get_string('err_'.$rule['type'], 'form', $a);
1188 if (strpos($str, '[[')!==0){
1189 $this->_rules[$field][$key]['message']=$str;
1196 function getLockOptionEndScript(){
1198 $iname = $this->getAttribute('id').'items';
1199 $js = '<script type="text/javascript">'."\n";
1200 $js .= '//<![CDATA['."\n";
1201 $js .= "var $iname = Array();\n";
1203 foreach ($this->_dependencies as $dependentOn => $conditions){
1204 $js .= "{$iname}['$dependentOn'] = Array();\n";
1205 foreach ($conditions as $condition=>$values) {
1206 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1207 foreach ($values as $value=>$dependents) {
1208 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1209 $i = 0;
1210 foreach ($dependents as $dependent) {
1211 $elements = $this->_getElNamesRecursive($dependent);
1212 foreach($elements as $element) {
1213 if ($element == $dependentOn) {
1214 continue;
1216 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1217 $i++;
1223 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1224 $js .='//]]>'."\n";
1225 $js .='</script>'."\n";
1226 return $js;
1229 function _getElNamesRecursive($element, $group=null){
1230 if ($group==null){
1231 $el = $this->getElement($element);
1232 } else {
1233 $el = &$element;
1235 if (is_a($el, 'HTML_QuickForm_group')){
1236 $group = $el;
1237 $elsInGroup = $group->getElements();
1238 $elNames = array();
1239 foreach ($elsInGroup as $elInGroup){
1240 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1242 }else{
1243 if ($group != null){
1244 $elNames = array($group->getElementName($el->getName()));
1245 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1246 return null;
1247 } elseif (is_a($el, 'HTML_QuickForm_hidden')) {
1248 return null;
1249 } elseif (method_exists($el, 'getPrivateName')) {
1250 return array($el->getPrivateName());
1251 } else {
1252 $elNames = array($el->getName());
1255 return $elNames;
1259 * Adds a dependency for $elementName which will be disabled if $condition is met.
1260 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1261 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1262 * is checked. If $condition is something else then it is checked to see if the value
1263 * of the $dependentOn element is equal to $condition.
1265 * @param string $elementName the name of the element which will be disabled
1266 * @param string $dependentOn the name of the element whose state will be checked for
1267 * condition
1268 * @param string $condition the condition to check
1269 * @param mixed $value used in conjunction with condition.
1271 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1272 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1273 $this->_dependencies[$dependentOn] = array();
1275 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1276 $this->_dependencies[$dependentOn][$condition] = array();
1278 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1279 $this->_dependencies[$dependentOn][$condition][$value] = array();
1281 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1284 function registerNoSubmitButton($buttonname){
1285 $this->_noSubmitButtons[]=$buttonname;
1288 function isNoSubmitButton($buttonname){
1289 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1292 function _registerCancelButton($addfieldsname){
1293 $this->_cancelButtons[]=$addfieldsname;
1296 * Displays elements without HTML input tags.
1297 * This method is different to freeze() in that it makes sure no hidden
1298 * elements are included in the form.
1299 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1301 * This function also removes all previously defined rules.
1303 * @param mixed $elementList array or string of element(s) to be frozen
1304 * @since 1.0
1305 * @access public
1306 * @throws HTML_QuickForm_Error
1308 function hardFreeze($elementList=null)
1310 if (!isset($elementList)) {
1311 $this->_freezeAll = true;
1312 $elementList = array();
1313 } else {
1314 if (!is_array($elementList)) {
1315 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1317 $elementList = array_flip($elementList);
1320 foreach (array_keys($this->_elements) as $key) {
1321 $name = $this->_elements[$key]->getName();
1322 if ($this->_freezeAll || isset($elementList[$name])) {
1323 $this->_elements[$key]->freeze();
1324 $this->_elements[$key]->setPersistantFreeze(false);
1325 unset($elementList[$name]);
1327 // remove all rules
1328 $this->_rules[$name] = array();
1329 // if field is required, remove the rule
1330 $unset = array_search($name, $this->_required);
1331 if ($unset !== false) {
1332 unset($this->_required[$unset]);
1337 if (!empty($elementList)) {
1338 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);
1340 return true;
1341 } // end func hardFreeze
1343 // }}}
1348 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1349 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1351 * Stylesheet is part of standard theme and should be automatically included.
1353 * @author Jamie Pratt <me@jamiep.org>
1354 * @license gpl license
1356 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
1359 * Element template array
1360 * @var array
1361 * @access private
1363 var $_elementTemplates;
1365 * Template used when opening a hidden fieldset
1366 * (i.e. a fieldset that is opened when there is no header element)
1367 * @var string
1368 * @access private
1370 // var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\">";
1371 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1373 * Header Template string
1374 * @var string
1375 * @access private
1377 var $_headerTemplate =
1378 // "\n\t\t<legend>{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div>\n\t\t";
1379 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1382 * Template used when opening a fieldset
1383 * @var string
1384 * @access private
1386 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1389 * Template used when closing a fieldset
1390 * @var string
1391 * @access private
1393 // var $_closeFieldsetTemplate = "\n\t\t</fieldset>";
1394 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1397 * Required Note template string
1398 * @var string
1399 * @access private
1401 var $_requiredNoteTemplate =
1402 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1404 var $_advancedElements = array();
1407 * Whether to display advanced elements (on page load)
1409 * @var integer 1 means show 0 means hide
1411 var $_showAdvanced;
1413 function MoodleQuickForm_Renderer(){
1414 // switch next two lines for ol li containers for form items.
1415 // $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>');
1416 $this->_elementTemplates = array(
1417 '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>',
1419 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
1421 'static'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>');
1423 parent::HTML_QuickForm_Renderer_Tableless();
1426 function setAdvancedElements($elements){
1427 $this->_advancedElements = $elements;
1431 * What to do when starting the form
1433 * @param MoodleQuickForm $form
1435 function startForm(&$form){
1436 $this->_reqHTML = $form->getReqHTML();
1437 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
1438 $this->_advancedHTML = $form->getAdvancedHTML();
1439 $this->_showAdvanced = $form->getShowAdvanced();
1440 parent::startForm($form);
1443 function startGroup(&$group, $required, $error){
1444 if (method_exists($group, 'getElementTemplateType')){
1445 $html = $this->_elementTemplates[$group->getElementTemplateType()];
1446 }else{
1447 $html = $this->_elementTemplates['default'];
1450 if ($this->_showAdvanced){
1451 $advclass = ' advanced';
1452 } else {
1453 $advclass = ' advanced hide';
1455 if (isset($this->_advancedElements[$group->getName()])){
1456 $html =str_replace(' {advanced}', $advclass, $html);
1457 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1458 } else {
1459 $html =str_replace(' {advanced}', '', $html);
1460 $html =str_replace('{advancedimg}', '', $html);
1462 if (method_exists($group, 'getHelpButton')){
1463 $html =str_replace('{help}', $group->getHelpButton(), $html);
1464 }else{
1465 $html =str_replace('{help}', '', $html);
1467 $html =str_replace('{name}', $group->getName(), $html);
1468 $html =str_replace('{type}', 'fgroup', $html);
1470 $this->_templates[$group->getName()]=$html;
1471 // Fix for bug in tableless quickforms that didn't allow you to stop a
1472 // fieldset before a group of elements.
1473 // if the element name indicates the end of a fieldset, close the fieldset
1474 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1475 && $this->_fieldsetsOpen > 0
1477 $this->_html .= $this->_closeFieldsetTemplate;
1478 $this->_fieldsetsOpen--;
1480 parent::startGroup($group, $required, $error);
1483 function renderElement(&$element, $required, $error){
1484 //manipulate id of all elements before rendering
1485 if (!is_null($element->getAttribute('id'))) {
1486 $id = $element->getAttribute('id');
1487 } else {
1488 $id = $element->getName();
1490 //strip qf_ prefix and replace '[' with '_' and strip ']'
1491 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1492 if (strpos($id, 'id_') !== 0){
1493 $element->updateAttributes(array('id'=>'id_'.$id));
1496 //adding stuff to place holders in template
1497 if (method_exists($element, 'getElementTemplateType')){
1498 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1499 }else{
1500 $html = $this->_elementTemplates['default'];
1502 if ($this->_showAdvanced){
1503 $advclass = ' advanced';
1504 } else {
1505 $advclass = ' advanced hide';
1507 if (isset($this->_advancedElements[$element->getName()])){
1508 $html =str_replace(' {advanced}', $advclass, $html);
1509 } else {
1510 $html =str_replace(' {advanced}', '', $html);
1512 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1513 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1514 } else {
1515 $html =str_replace('{advancedimg}', '', $html);
1517 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1518 $html =str_replace('{name}', $element->getName(), $html);
1519 if (method_exists($element, 'getHelpButton')){
1520 $html = str_replace('{help}', $element->getHelpButton(), $html);
1521 }else{
1522 $html = str_replace('{help}', '', $html);
1526 if (!isset($this->_templates[$element->getName()])) {
1527 $this->_templates[$element->getName()] = $html;
1530 parent::renderElement($element, $required, $error);
1533 function finishForm(&$form){
1534 parent::finishForm($form);
1535 // add a lockoptions script
1536 if ('' != ($script = $form->getLockOptionEndScript())) {
1537 $this->_html = $this->_html . "\n" . $script;
1541 * Called when visiting a header element
1543 * @param object An HTML_QuickForm_header element being visited
1544 * @access public
1545 * @return void
1547 function renderHeader(&$header) {
1548 $name = $header->getName();
1550 $id = empty($name) ? '' : ' id="' . $name . '"';
1551 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1552 if (is_null($header->_text)) {
1553 $header_html = '';
1554 } elseif (!empty($name) && isset($this->_templates[$name])) {
1555 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1556 } else {
1557 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1560 if (isset($this->_advancedElements[$name])){
1561 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1562 } else {
1563 $header_html =str_replace('{advancedimg}', '', $header_html);
1565 $elementName='mform_showadvanced';
1566 if ($this->_showAdvanced==0){
1567 $buttonlabel = get_string('showadvanced', 'form');
1568 } else {
1569 $buttonlabel = get_string('hideadvanced', 'form');
1572 if (isset($this->_advancedElements[$name])){
1573 $showtext="'".get_string('showadvanced', 'form')."'";
1574 $hidetext="'".get_string('hideadvanced', 'form')."'";
1575 //onclick returns false so if js is on then page is not submitted.
1576 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1577 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1578 $header_html =str_replace('{button}', $button, $header_html);
1579 } else {
1580 $header_html =str_replace('{button}', '', $header_html);
1583 if ($this->_fieldsetsOpen > 0) {
1584 $this->_html .= $this->_closeFieldsetTemplate;
1585 $this->_fieldsetsOpen--;
1588 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1589 if ($this->_showAdvanced){
1590 $advclass = ' class="advanced"';
1591 } else {
1592 $advclass = ' class="advanced hide"';
1594 if (isset($this->_advancedElements[$name])){
1595 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1596 } else {
1597 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1599 $this->_html .= $openFieldsetTemplate . $header_html;
1600 $this->_fieldsetsOpen++;
1601 } // end func renderHeader
1603 function getStopFieldsetElements(){
1604 return $this->_stopFieldsetElements;
1609 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1611 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1612 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1613 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1614 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1615 MoodleQuickForm::registerElementType('passwordreveal', "$CFG->libdir/form/passwordreveal.php", 'MoodleQuickForm_passwordreveal');
1616 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1617 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1618 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1619 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1620 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1621 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1622 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1623 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1624 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1625 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1626 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1627 MoodleQuickForm::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
1628 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1629 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1630 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1631 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1632 MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1633 MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1634 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1635 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1636 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1637 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');