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
10 * See examples of use of this library in course/edit.php and course/edit_form.php
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.
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';
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');
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.
58 var $_formname; // form name
60 * quickform object definition
62 * @var MoodleQuickForm
76 var $_upload_manager; //
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
91 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
92 * current url. If a moodle_url object then outputs params as hidden variables.
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
101 * @param mixed $attributes you can pass a string of html attributes here or an array.
104 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
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);
113 $this->_form
->hardFreeze();
115 $this->set_upload_manager(new upload_manager());
119 $this->_form
->addElement('hidden', 'sesskey', null); // automatic sesskey protection
120 $this->_form
->setDefault('sesskey', sesskey());
121 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
122 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
123 $this->_form
->_setDefaultRuleMessages();
125 // we have to know all input types before processing submission ;-)
126 $this->_process_submission($method);
128 // update form definition based on final data
129 $this->definition_after_data();
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);
150 $el = array_shift($elkeys);
151 $names = $form->_getElNamesRecursive($el);
154 $name=array_shift($names);
156 $focus='forms[\''.$this->_form
->getAttribute('id').'\'].elements[\''.$name.'\']';
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;
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!');
182 $submission = 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
202 $mform =& $this->_form
;
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
216 $errors[$elname] = $this->_upload_manager
->files
[$elname]['uploadlog'];
219 error('Incorrect upload attempt!');
223 // return errors if found
224 if ($status and 0 == count($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);
245 //update form definition when data changed
246 $this->definition_after_data();
250 * Set custom upload manager.
251 * Must be used BEFORE creating of file element!
253 * @param object $um - custom upload manager
255 function set_upload_manager($um=false) {
257 $um = new upload_manager();
259 $this->_upload_manager
= $um;
261 $this->_form
->setMaxFileSize($um->config
->maxbytes
);
265 * Check that form was submitted. Does not check validity of submitted data.
267 * @return bool true if form properly submitted
269 function is_submitted() {
270 return $this->_form
->isSubmitted();
273 function no_submit_button_pressed(){
274 static $nosubmit = null; // one check is enough
275 if (!is_null($nosubmit)){
278 $mform =& $this->_form
;
280 if (!$this->is_submitted()){
283 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
284 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
294 * Check that form data is valid.
296 * @return bool true if form data valid
298 function is_validated() {
299 static $validated = null; // one validation is enough
300 $mform =& $this->_form
;
302 if ($this->no_submit_button_pressed()){
304 } elseif ($validated === null) {
305 $internal_val = $mform->validate();
306 $moodle_val = $this->validation($mform->exportValues(null, true));
307 if ($moodle_val !== true) {
308 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
309 foreach ($moodle_val as $element=>$msg) {
310 $mform->setElementError($element, $msg);
317 $file_val = $this->_validate_files();
318 if ($file_val !== true) {
319 if (!empty($file_val)) {
320 foreach ($file_val as $element=>$msg) {
321 $mform->setElementError($element, $msg);
326 $validated = ($internal_val and $moodle_val and $file_val);
332 * Return true if a cancel button has been pressed resulting in the form being submitted.
334 * @return boolean true if a cancel button has been pressed
336 function is_cancelled(){
337 $mform =& $this->_form
;
338 if ($mform->isSubmitted()){
339 foreach ($mform->_cancelButtons
as $cancelbutton){
340 if (optional_param($cancelbutton, 0, PARAM_RAW
)){
349 * Return submitted data if properly submitted or returns NULL if validation fails or
350 * if there is no submitted data.
352 * @param bool $slashed true means return data with addslashes applied
353 * @return object submitted data; NULL if not valid or not submitted
355 function get_data($slashed=true) {
356 $mform =& $this->_form
;
358 if ($this->is_submitted() and $this->is_validated()) {
359 $data = $mform->exportValues(null, $slashed);
360 unset($data['sesskey']); // we do not need to return sesskey
361 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
365 return (object)$data;
373 * Save verified uploaded files into directory. Upload process can be customised from definition()
374 * method by creating instance of upload manager and storing it in $this->_upload_form
376 * @param string $destination where to store uploaded files
377 * @return bool success
379 function save_files($destination) {
380 if ($this->is_submitted() and $this->is_validated()) {
381 return $this->_upload_manager
->save_files($destination);
387 * If we're only handling one file (if inputname was given in the constructor)
388 * this will return the (possibly changed) filename of the file.
389 * @return mixed false in case of failure, string if ok
391 function get_new_filename() {
392 return $this->_upload_manager
->get_new_filename();
399 $this->_form
->display();
403 * Abstract method - always override!
405 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
407 function definition() {
408 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
412 * Dummy stub method - override if you need to setup the form depending on current
413 * values. This method is called after definition(), data submission and set_data().
414 * All form setup that is dependent on form values should go in here.
416 function definition_after_data(){
420 * Dummy stub method - override if you needed to perform some extra validation.
421 * If there are errors return array of errors ("fieldname"=>"error message"),
422 * otherwise true if ok.
424 * @param array $data array of ("fieldname"=>value) of submitted data
425 * @return bool array of errors or true if ok
427 function validation($data) {
436 * Method to add a repeating group of elements to a form.
438 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
439 * @param integer $repeats no of times to repeat elements initially
440 * @param array $options Array of options to apply to elements. Array keys are element names.
441 * This is an array of arrays. The second sets of keys are the option types
443 * 'default' - default value is value
444 * 'type' - PARAM_* constant is value
445 * 'helpbutton' - helpbutton params array is value
446 * 'disabledif' - last three moodleform::disabledIf()
447 * params are value as an array
448 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
449 * @param string $addfieldsname name for button to add more fields
450 * @param int $addfieldsno how many fields to add at a time
451 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
452 * @return int no of repeats of element in this page
454 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, $addfieldsname, $addfieldsno=5, $addstring=null){
455 if ($addstring===null){
456 $addstring = get_string('addfields', 'form', $addfieldsno);
458 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
460 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT
);
461 $addfields = optional_param($addfieldsname, '', PARAM_TEXT
);
462 if (!empty($addfields)){
463 $repeats +
= $addfieldsno;
465 $mform =& $this->_form
;
466 $mform->registerNoSubmitButton($addfieldsname);
467 $mform->addElement('hidden', $repeathiddenname, $repeats);
468 //value not to be overridden by submitted value
469 $mform->setConstants(array($repeathiddenname=>$repeats));
470 for ($i=0; $i<$repeats; $i++
) {
471 foreach ($elementobjs as $elementobj){
472 $elementclone = clone($elementobj);
473 $name = $elementclone->getName();
475 $elementclone->setName($name."[$i]");
477 if (is_a($elementclone, 'HTML_QuickForm_header')){
478 $value=$elementclone->_text
;
479 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
482 $value=$elementclone->getLabel();
483 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
487 $mform->addElement($elementclone);
490 for ($i=0; $i<$repeats; $i++
) {
491 foreach ($options as $elementname => $elementoptions){
492 $pos=strpos($elementname, '[');
494 $realelementname = substr($elementname, 0, $pos+
1)."[$i]";
495 $realelementname .= substr($elementname, $pos+
1);
497 $realelementname = $elementname."[$i]";
499 foreach ($elementoptions as $option => $params){
503 $mform->setDefault($realelementname, $params);
506 $mform->setHelpButton($realelementname, $params);
509 $params = array_merge(array($realelementname), $params);
510 call_user_func_array(array(&$mform, 'disabledIf'), $params);
513 if (is_string($params)){
514 $params = array(null, $params, null, 'client');
516 $params = array_merge(array($realelementname), $params);
517 call_user_func_array(array(&$mform, 'addRule'), $params);
524 $mform->addElement('submit', $addfieldsname, $addstring);
526 $mform->closeHeaderBefore($addfieldsname);
531 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
532 * if you don't want a cancel button in your form. If you have a cancel button make sure you
533 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
534 * get data with get_data().
536 * @param boolean $cancel whether to show cancel button, default true
537 * @param boolean $revert whether to show revert button, default true
538 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
540 function add_action_buttons($cancel = true, $submitlabel=null){
541 if (is_null($submitlabel)){
542 $submitlabel = get_string('savechanges');
544 $mform =& $this->_form
;
546 //when two elements we need a group
547 $buttonarray=array();
548 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
549 $buttonarray[] = &$mform->createElement('cancel');
550 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
551 $mform->closeHeaderBefore('buttonar');
554 $mform->addElement('submit', 'submitbutton', $submitlabel);
555 $mform->closeHeaderBefore('submitbutton');
561 * You never extend this class directly. The class methods of this class are available from
562 * the private $this->_form property on moodleform and it's children. You generally only
563 * call methods on this class from within abstract methods that you override on moodleform such
564 * as definition and definition_after_data
567 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
568 var $_types = array();
569 var $_dependencies = array();
571 * Array of buttons that if pressed do not result in the processing of the form.
575 var $_noSubmitButtons=array();
577 * Array of buttons that if pressed do not result in the processing of the form.
581 var $_cancelButtons=array();
584 * Array whose keys are element names. If the key exists this is a advanced element
588 var $_advancedElements = array();
591 * Whether to display advanced elements (on page load)
595 var $_showAdvanced = null;
598 * The form name is derrived from the class name of the wrapper minus the trailing form
599 * It is a name with words joined by underscores whereas the id attribute is words joined by
607 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
611 var $_pageparams = '';
614 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
615 * @param string $formName Form's name.
616 * @param string $method (optional)Form's method defaults to 'POST'
617 * @param mixed $action (optional)Form's action - string or moodle_url
618 * @param string $target (optional)Form's target defaults to none
619 * @param mixed $attributes (optional)Extra attributes for <form> tag
620 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
623 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
626 static $formcounter = 1;
628 HTML_Common
::HTML_Common($attributes);
629 $target = empty($target) ?
array() : array('target' => $target);
630 $this->_formName
= $formName;
631 if (is_a($action, 'moodle_url')){
632 $this->_pageparams
= $action->hidden_params_out();
633 $action = $action->out(true);
635 $this->_pageparams
= '';
637 //no 'name' atttribute for form in xhtml strict :
638 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) +
$target;
640 $this->updateAttributes($attributes);
642 //this is custom stuff for Moodle :
643 $oldclass= $this->getAttribute('class');
644 if (!empty($oldclass)){
645 $this->updateAttributes(array('class'=>$oldclass.' mform'));
647 $this->updateAttributes(array('class'=>'mform'));
649 $this->_reqHTML
= '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />';
650 $this->_advancedHTML
= '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath
.'/adv.gif'.'" />';
651 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />'));
652 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
656 * Use this method to indicate an element in a form is an advanced field. If items in a form
657 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
658 * form so the user can decide whether to display advanced form controls.
660 * If you set a header element to advanced then all elements it contains will also be set as advanced.
662 * @param string $elementName group or element name (not the element name of something inside a group).
663 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
665 function setAdvanced($elementName, $advanced=true){
667 $this->_advancedElements
[$elementName]='';
668 } elseif (isset($this->_advancedElements
[$elementName])) {
669 unset($this->_advancedElements
[$elementName]);
671 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
672 $this->setShowAdvanced();
673 $this->registerNoSubmitButton('mform_showadvanced');
675 $this->addElement('hidden', 'mform_showadvanced_last');
679 * Set whether to show advanced elements in the form on first displaying form. Default is not to
680 * display advanced elements in the form until 'Show Advanced' is pressed.
682 * You can get the last state of the form and possibly save it for this user by using
683 * value 'mform_showadvanced_last' in submitted data.
685 * @param boolean $showadvancedNow
687 function setShowAdvanced($showadvancedNow = null){
688 if ($showadvancedNow === null){
689 if ($this->_showAdvanced
!== null){
691 } else { //if setShowAdvanced is called without any preference
692 //make the default to not show advanced elements.
693 $showadvancedNow = get_user_preferences(
694 moodle_strtolower($this->_formName
.'_showadvanced', 0));
697 //value of hidden element
698 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT
);
700 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW
);
701 //toggle if button pressed or else stay the same
702 if ($hiddenLast == -1) {
703 $next = $showadvancedNow;
704 } elseif ($buttonPressed) { //toggle on button press
705 $next = !$hiddenLast;
709 $this->_showAdvanced
= $next;
710 if ($showadvancedNow != $next){
711 set_user_preference($this->_formName
.'_showadvanced', $next);
713 $this->setConstants(array('mform_showadvanced_last'=>$next));
715 function getShowAdvanced(){
716 return $this->_showAdvanced
;
723 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
728 function accept(&$renderer)
730 if (method_exists($renderer, 'setAdvancedElements')){
731 //check for visible fieldsets where all elements are advanced
732 //and mark these headers as advanced as well.
733 //And mark all elements in a advanced header as advanced
734 $stopFields = $renderer->getStopFieldSetElements();
736 $lastHeaderAdvanced = false;
737 $anyAdvanced = false;
738 foreach (array_keys($this->_elements
) as $elementIndex){
739 $element =& $this->_elements
[$elementIndex];
740 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
741 if ($anyAdvanced && ($lastHeader!==null)){
742 $this->setAdvanced($lastHeader->getName());
744 $lastHeaderAdvanced = false;
745 } elseif ($lastHeaderAdvanced) {
746 $this->setAdvanced($element->getName());
748 if ($element->getType()=='header'){
749 $lastHeader =& $element;
750 $anyAdvanced = false;
751 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
752 } elseif (isset($this->_advancedElements
[$element->getName()])){
756 $renderer->setAdvancedElements($this->_advancedElements
);
759 parent
::accept($renderer);
764 function closeHeaderBefore($elementName){
765 $renderer =& $this->defaultRenderer();
766 $renderer->addStopFieldsetElements($elementName);
770 * Should be used for all elements of a form except for select, radio and checkboxes which
771 * clean their own data.
773 * @param string $elementname
774 * @param integer $paramtype use the constants PARAM_*.
775 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
776 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
777 * It will strip all html tags. But will still let tags for multilang support
779 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
780 * html editor. Data from the editor is later cleaned before display using
781 * format_text() function. PARAM_RAW can also be used for data that is validated
782 * by some other way or printed by p() or s().
783 * * PARAM_INT should be used for integers.
784 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
787 function setType($elementname, $paramtype) {
788 $this->_types
[$elementname] = $paramtype;
792 * See description of setType above. This can be used to set several types at once.
794 * @param array $paramtypes
796 function setTypes($paramtypes) {
797 $this->_types
= $paramtypes +
$this->_types
;
800 function updateSubmission($submission, $files) {
801 $this->_flagSubmitted
= false;
803 if (empty($submission)) {
804 $this->_submitValues
= array();
806 foreach ($submission as $key=>$s) {
807 if (array_key_exists($key, $this->_types
)) {
808 $submission[$key] = clean_param($s, $this->_types
[$key]);
811 $this->_submitValues
= $this->_recursiveFilter('stripslashes', $submission);
812 $this->_flagSubmitted
= true;
816 $this->_submitFiles
= array();
818 if (1 == get_magic_quotes_gpc()) {
819 foreach (array_keys($files) as $elname) {
820 // dangerous characters in filenames are cleaned later in upload_manager
821 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
824 $this->_submitFiles
= $files;
825 $this->_flagSubmitted
= true;
828 // need to tell all elements that they need to update their value attribute.
829 foreach (array_keys($this->_elements
) as $key) {
830 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
834 function getReqHTML(){
835 return $this->_reqHTML
;
838 function getAdvancedHTML(){
839 return $this->_advancedHTML
;
843 * Initializes a default form value. Used to specify the default for a new entry where
844 * no data is loaded in using moodleform::set_data()
846 * @param string $elementname element name
847 * @param mixed $values values for that element name
848 * @param bool $slashed the default value is slashed
852 function setDefault($elementName, $defaultValue, $slashed=false){
853 $filter = $slashed ?
'stripslashes' : NULL;
854 $this->setDefaults(array($elementName=>$defaultValue), $filter);
855 } // end func setDefault
857 * Add an array of buttons to the form
858 * @param array $buttons An associative array representing help button to attach to
859 * to the form. keys of array correspond to names of elements in form.
863 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
865 foreach ($buttons as $elementname => $button){
866 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
870 * Add a single button.
872 * @param string $elementname name of the element to add the item to
873 * @param array $button - arguments to pass to function $function
874 * @param boolean $suppresscheck - whether to throw an error if the element
876 * @param string $function - function to generate html from the arguments in $button
878 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
879 if (array_key_exists($elementname, $this->_elementIndex
)){
880 //_elements has a numeric index, this code accesses the elements by name
881 $element=&$this->_elements
[$this->_elementIndex
[$elementname]];
882 if (method_exists($element, 'setHelpButton')){
883 $element->setHelpButton($button, $function);
886 $a->name
=$element->getName();
887 $a->classname
=get_class($element);
888 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
890 }elseif (!$suppresscheck){
891 print_error('nonexistentformelements', 'form', '', $elementname);
895 function exportValues($elementList= null, $addslashes=true){
896 $unfiltered = array();
897 if (null === $elementList) {
898 // iterate over all elements, calling their exportValue() methods
899 $emptyarray = array();
900 foreach (array_keys($this->_elements
) as $key) {
901 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
){
902 $value = $this->_elements
[$key]->exportValue($emptyarray, true);
904 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
907 if (is_array($value)) {
908 // This shit throws a bogus warning in PHP 4.3.x
909 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
913 if (!is_array($elementList)) {
914 $elementList = array_map('trim', explode(',', $elementList));
916 foreach ($elementList as $elementName) {
917 $value = $this->exportValue($elementName);
918 if (PEAR
::isError($value)) {
921 $unfiltered[$elementName] = $value;
926 return $this->_recursiveFilter('addslashes', $unfiltered);
932 * Adds a validation rule for the given field
934 * If the element is in fact a group, it will be considered as a whole.
935 * To validate grouped elements as separated entities,
936 * use addGroupRule instead of addRule.
938 * @param string $element Form element name
939 * @param string $message Message to display for invalid data
940 * @param string $type Rule type, use getRegisteredRules() to get types
941 * @param string $format (optional)Required for extra rule data
942 * @param string $validation (optional)Where to perform validation: "server", "client"
943 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
944 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
947 * @throws HTML_QuickForm_Error
949 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
951 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
952 if ($validation == 'client') {
953 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
956 } // end func addRule
958 * Adds a validation rule for the given group of elements
960 * Only groups with a name can be assigned a validation rule
961 * Use addGroupRule when you need to validate elements inside the group.
962 * Use addRule if you need to validate the group as a whole. In this case,
963 * the same rule will be applied to all elements in the group.
964 * Use addRule if you need to validate the group against a function.
966 * @param string $group Form group name
967 * @param mixed $arg1 Array for multiple elements or error message string for one element
968 * @param string $type (optional)Rule type use getRegisteredRules() to get types
969 * @param string $format (optional)Required for extra rule data
970 * @param int $howmany (optional)How many valid elements should be in the group
971 * @param string $validation (optional)Where to perform validation: "server", "client"
972 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
975 * @throws HTML_QuickForm_Error
977 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
979 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
980 if (is_array($arg1)) {
981 foreach ($arg1 as $rules) {
982 foreach ($rules as $rule) {
983 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
985 if ('client' == $validation) {
986 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
990 } elseif (is_string($arg1)) {
992 if ($validation == 'client') {
993 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
996 } // end func addGroupRule
1000 * Returns the client side validation script
1002 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1003 * and slightly modified to run rules per-element
1004 * Needed to override this because of an error with client side validation of grouped elements.
1007 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1009 function getValidationScript()
1011 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1015 include_once('HTML/QuickForm/RuleRegistry.php');
1016 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1027 foreach ($this->_rules
as $elementName => $rules) {
1028 foreach ($rules as $rule) {
1029 if ('client' == $rule['validation']) {
1030 unset($element); //TODO: find out how to properly initialize it
1032 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1033 $rule['message'] = strtr($rule['message'], $js_escape);
1035 if (isset($rule['group'])) {
1036 $group =& $this->getElement($rule['group']);
1037 // No JavaScript validation for frozen elements
1038 if ($group->isFrozen()) {
1041 $elements =& $group->getElements();
1042 foreach (array_keys($elements) as $key) {
1043 if ($elementName == $group->getElementName($key)) {
1044 $element =& $elements[$key];
1048 } elseif ($dependent) {
1050 $element[] =& $this->getElement($elementName);
1051 foreach ($rule['dependent'] as $elName) {
1052 $element[] =& $this->getElement($elName);
1055 $element =& $this->getElement($elementName);
1057 // No JavaScript validation for frozen elements
1058 if (is_object($element) && $element->isFrozen()) {
1060 } elseif (is_array($element)) {
1061 foreach (array_keys($element) as $key) {
1062 if ($element[$key]->isFrozen()) {
1067 // Fix for bug displaying errors for elements in a group
1068 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1069 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1070 $test[$elementName][1]=$element;
1076 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1077 // the form, and then that form field gets corrupted by the code that follows.
1081 <script type="text/javascript">
1084 var skipClientValidation = false;
1086 function qf_errorHandler(element, _qfMsg) {
1087 div = element.parentNode;
1088 if (_qfMsg != \'\') {
1089 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1091 errorSpan = document.createElement("span");
1092 errorSpan.id = \'id_error_\'+element.name;
1093 errorSpan.className = "error";
1094 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1097 while (errorSpan.firstChild) {
1098 errorSpan.removeChild(errorSpan.firstChild);
1101 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1102 errorSpan.appendChild(document.createElement("br"));
1104 if (div.className.substr(div.className.length - 6, 6) != " error"
1105 && div.className != "error") {
1106 div.className += " error";
1111 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1113 errorSpan.parentNode.removeChild(errorSpan);
1116 if (div.className.substr(div.className.length - 6, 6) == " error") {
1117 div.className = div.className.substr(0, div.className.length - 6);
1118 } else if (div.className == "error") {
1126 foreach ($test as $elementName => $jsandelement) {
1127 // Fix for bug displaying errors for elements in a group
1129 list($jsArr,$element)=$jsandelement;
1132 function validate_' . $this->_formName
. '_' . $elementName . '(element) {
1134 var errFlag = new Array();
1137 var frm = element.parentNode;
1138 while (frm && frm.nodeName != "FORM") {
1139 frm = frm.parentNode;
1141 ' . join("\n", $jsArr) . '
1142 return qf_errorHandler(element, _qfMsg);
1146 ret = validate_' . $this->_formName
. '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1147 if (!ret && !first_focus) {
1149 frm.elements[\''.$elementName.'\'].focus();
1153 // Fix for bug displaying errors for elements in a group
1155 //$element =& $this->getElement($elementName);
1157 $valFunc = 'validate_' . $this->_formName
. '_' . $elementName . '(this)';
1158 $onBlur = $element->getAttribute('onBlur');
1159 $onChange = $element->getAttribute('onChange');
1160 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1161 'onChange' => $onChange . $valFunc));
1163 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1165 function validate_' . $this->_formName
. '(frm) {
1166 if (skipClientValidation) {
1171 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1172 var first_focus = false;
1173 ' . $validateJS . ';
1179 } // end func getValidationScript
1180 function _setDefaultRuleMessages(){
1181 foreach ($this->_rules
as $field => $rulesarr){
1182 foreach ($rulesarr as $key => $rule){
1183 if ($rule['message']===null){
1185 $a->format
=$rule['format'];
1186 $str=get_string('err_'.$rule['type'], 'form', $a);
1187 if (strpos($str, '[[')!==0){
1188 $this->_rules
[$field][$key]['message']=$str;
1195 function getLockOptionEndScript(){
1197 $iname = $this->getAttribute('id').'items';
1198 $js = '<script type="text/javascript">'."\n";
1199 $js .= '//<![CDATA['."\n";
1200 $js .= "var $iname = Array();\n";
1202 foreach ($this->_dependencies
as $dependentOn => $conditions){
1203 $js .= "{$iname}['$dependentOn'] = Array();\n";
1204 foreach ($conditions as $condition=>$values) {
1205 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1206 foreach ($values as $value=>$dependents) {
1207 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1209 foreach ($dependents as $dependent) {
1210 $elements = $this->_getElNamesRecursive($dependent);
1211 foreach($elements as $element) {
1212 if ($element == $dependentOn) {
1215 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1222 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1224 $js .='</script>'."\n";
1228 function _getElNamesRecursive($element, $group=null){
1230 $el = $this->getElement($element);
1234 if (is_a($el, 'HTML_QuickForm_group')){
1236 $elsInGroup = $group->getElements();
1238 foreach ($elsInGroup as $elInGroup){
1239 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1242 if ($group != null){
1243 $elNames = array($group->getElementName($el->getName()));
1244 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1246 } elseif (is_a($el, 'HTML_QuickForm_hidden')) {
1248 } elseif (method_exists($el, 'getPrivateName')) {
1249 return array($el->getPrivateName());
1251 $elNames = array($el->getName());
1258 * Adds a dependency for $elementName which will be disabled if $condition is met.
1259 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1260 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1261 * is checked. If $condition is something else then it is checked to see if the value
1262 * of the $dependentOn element is equal to $condition.
1264 * @param string $elementName the name of the element which will be disabled
1265 * @param string $dependentOn the name of the element whose state will be checked for
1267 * @param string $condition the condition to check
1268 * @param mixed $value used in conjunction with condition.
1270 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1271 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
1272 $this->_dependencies
[$dependentOn] = array();
1274 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
1275 $this->_dependencies
[$dependentOn][$condition] = array();
1277 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
1278 $this->_dependencies
[$dependentOn][$condition][$value] = array();
1280 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
1283 function registerNoSubmitButton($buttonname){
1284 $this->_noSubmitButtons
[]=$buttonname;
1287 function isNoSubmitButton($buttonname){
1288 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
1291 function _registerCancelButton($addfieldsname){
1292 $this->_cancelButtons
[]=$addfieldsname;
1295 * Displays elements without HTML input tags.
1296 * This method is different to freeze() in that it makes sure no hidden
1297 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1300 * This function also removes all previously defined rules.
1302 * @param mixed $elementList array or string of element(s) to be frozen
1305 * @throws HTML_QuickForm_Error
1307 function hardFreeze($elementList=null)
1309 if (!isset($elementList)) {
1310 $this->_freezeAll
= true;
1311 $elementList = array();
1313 if (!is_array($elementList)) {
1314 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1316 $elementList = array_flip($elementList);
1319 foreach (array_keys($this->_elements
) as $key) {
1320 $name = $this->_elements
[$key]->getName();
1321 if ($this->_freezeAll ||
isset($elementList[$name])) {
1322 $this->_elements
[$key]->freeze();
1323 $this->_elements
[$key]->setPersistantFreeze(false);
1324 unset($elementList[$name]);
1327 $this->_rules
[$name] = array();
1328 // if field is required, remove the rule
1329 $unset = array_search($name, $this->_required
);
1330 if ($unset !== false) {
1331 unset($this->_required
[$unset]);
1336 if (!empty($elementList)) {
1337 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);
1342 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1344 * This function also removes all previously defined rules of elements it freezes.
1346 * @param array $elementList array or string of element(s) not to be frozen
1349 * @throws HTML_QuickForm_Error
1351 function hardFreezeAllVisibleExcept($elementList)
1353 $elementList = array_flip($elementList);
1354 foreach (array_keys($this->_elements
) as $key) {
1355 $name = $this->_elements
[$key]->getName();
1356 $type = $this->_elements
[$key]->getType();
1358 if ($type == 'hidden'){
1359 // leave hidden types as they are
1360 } elseif (!isset($elementList[$name])) {
1361 $this->_elements
[$key]->freeze();
1362 $this->_elements
[$key]->setPersistantFreeze(false);
1365 $this->_rules
[$name] = array();
1366 // if field is required, remove the rule
1367 $unset = array_search($name, $this->_required
);
1368 if ($unset !== false) {
1369 unset($this->_required
[$unset]);
1376 * Tells whether the form was already submitted
1378 * This is useful since the _submitFiles and _submitValues arrays
1379 * may be completely empty after the trackSubmit value is removed.
1384 function isSubmitted()
1386 return parent
::isSubmitted() && (!$this->isFrozen());
1392 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1393 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1395 * Stylesheet is part of standard theme and should be automatically included.
1397 * @author Jamie Pratt <me@jamiep.org>
1398 * @license gpl license
1400 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
1403 * Element template array
1407 var $_elementTemplates;
1409 * Template used when opening a hidden fieldset
1410 * (i.e. a fieldset that is opened when there is no header element)
1414 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\">";
1416 * Header Template string
1420 var $_headerTemplate =
1421 "\n\t\t<legend>{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div>\n\t\t";
1424 * Template used when opening a fieldset
1428 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1431 * Template used when closing a fieldset
1435 var $_closeFieldsetTemplate = "\n\t\t</fieldset>";
1438 * Required Note template string
1442 var $_requiredNoteTemplate =
1443 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1445 var $_advancedElements = array();
1448 * Whether to display advanced elements (on page load)
1450 * @var integer 1 means show 0 means hide
1454 function MoodleQuickForm_Renderer(){
1455 // switch next two lines for ol li containers for form items.
1456 // $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>');
1457 $this->_elementTemplates
= array(
1458 '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>',
1460 '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>',
1462 '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} </div></div>',
1466 parent
::HTML_QuickForm_Renderer_Tableless();
1469 function setAdvancedElements($elements){
1470 $this->_advancedElements
= $elements;
1474 * What to do when starting the form
1476 * @param MoodleQuickForm $form
1478 function startForm(&$form){
1479 $this->_reqHTML
= $form->getReqHTML();
1480 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
1481 $this->_advancedHTML
= $form->getAdvancedHTML();
1482 $this->_showAdvanced
= $form->getShowAdvanced();
1483 parent
::startForm($form);
1484 if ($form->isFrozen()){
1485 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
1487 $this->_hiddenHtml
.= $form->_pageparams
;
1493 function startGroup(&$group, $required, $error){
1494 if (method_exists($group, 'getElementTemplateType')){
1495 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
1497 $html = $this->_elementTemplates
['default'];
1500 if ($this->_showAdvanced
){
1501 $advclass = ' advanced';
1503 $advclass = ' advanced hide';
1505 if (isset($this->_advancedElements
[$group->getName()])){
1506 $html =str_replace(' {advanced}', $advclass, $html);
1507 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1509 $html =str_replace(' {advanced}', '', $html);
1510 $html =str_replace('{advancedimg}', '', $html);
1512 if (method_exists($group, 'getHelpButton')){
1513 $html =str_replace('{help}', $group->getHelpButton(), $html);
1515 $html =str_replace('{help}', '', $html);
1517 $html =str_replace('{name}', $group->getName(), $html);
1518 $html =str_replace('{type}', 'fgroup', $html);
1520 $this->_templates
[$group->getName()]=$html;
1521 // Fix for bug in tableless quickforms that didn't allow you to stop a
1522 // fieldset before a group of elements.
1523 // if the element name indicates the end of a fieldset, close the fieldset
1524 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
1525 && $this->_fieldsetsOpen
> 0
1527 $this->_html
.= $this->_closeFieldsetTemplate
;
1528 $this->_fieldsetsOpen
--;
1530 parent
::startGroup($group, $required, $error);
1533 function renderElement(&$element, $required, $error){
1534 //manipulate id of all elements before rendering
1535 if (!is_null($element->getAttribute('id'))) {
1536 $id = $element->getAttribute('id');
1538 $id = $element->getName();
1540 //strip qf_ prefix and replace '[' with '_' and strip ']'
1541 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1542 if (strpos($id, 'id_') !== 0){
1543 $element->updateAttributes(array('id'=>'id_'.$id));
1546 //adding stuff to place holders in template
1547 if (method_exists($element, 'getElementTemplateType')){
1548 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
1550 $html = $this->_elementTemplates
['default'];
1552 if ($this->_showAdvanced
){
1553 $advclass = ' advanced';
1555 $advclass = ' advanced hide';
1557 if (isset($this->_advancedElements
[$element->getName()])){
1558 $html =str_replace(' {advanced}', $advclass, $html);
1560 $html =str_replace(' {advanced}', '', $html);
1562 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
1563 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1565 $html =str_replace('{advancedimg}', '', $html);
1567 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1568 $html =str_replace('{name}', $element->getName(), $html);
1569 if (method_exists($element, 'getHelpButton')){
1570 $html = str_replace('{help}', $element->getHelpButton(), $html);
1572 $html = str_replace('{help}', '', $html);
1576 $this->_templates
[$element->getName()] = $html;
1578 parent
::renderElement($element, $required, $error);
1581 function finishForm(&$form){
1582 if ($form->isFrozen()){
1583 $this->_hiddenHtml
= '';
1585 parent
::finishForm($form);
1586 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1587 // add a lockoptions script
1588 $this->_html
= $this->_html
. "\n" . $script;
1592 * Called when visiting a header element
1594 * @param object An HTML_QuickForm_header element being visited
1598 function renderHeader(&$header) {
1599 $name = $header->getName();
1601 $id = empty($name) ?
'' : ' id="' . $name . '"';
1602 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1603 if (is_null($header->_text
)) {
1605 } elseif (!empty($name) && isset($this->_templates
[$name])) {
1606 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
1608 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
1611 if (isset($this->_advancedElements
[$name])){
1612 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
1614 $header_html =str_replace('{advancedimg}', '', $header_html);
1616 $elementName='mform_showadvanced';
1617 if ($this->_showAdvanced
==0){
1618 $buttonlabel = get_string('showadvanced', 'form');
1620 $buttonlabel = get_string('hideadvanced', 'form');
1623 if (isset($this->_advancedElements
[$name])){
1624 $showtext="'".get_string('showadvanced', 'form')."'";
1625 $hidetext="'".get_string('hideadvanced', 'form')."'";
1626 //onclick returns false so if js is on then page is not submitted.
1627 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1628 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1629 $header_html =str_replace('{button}', $button, $header_html);
1631 $header_html =str_replace('{button}', '', $header_html);
1634 if ($this->_fieldsetsOpen
> 0) {
1635 $this->_html
.= $this->_closeFieldsetTemplate
;
1636 $this->_fieldsetsOpen
--;
1639 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
1640 if ($this->_showAdvanced
){
1641 $advclass = ' class="advanced"';
1643 $advclass = ' class="advanced hide"';
1645 if (isset($this->_advancedElements
[$name])){
1646 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1648 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1650 $this->_html
.= $openFieldsetTemplate . $header_html;
1651 $this->_fieldsetsOpen++
;
1652 } // end func renderHeader
1654 function getStopFieldsetElements(){
1655 return $this->_stopFieldsetElements
;
1660 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1662 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1663 MoodleQuickForm
::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1664 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1665 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1666 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1667 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1668 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1669 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1670 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1671 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1672 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1673 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1674 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1675 MoodleQuickForm
::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1676 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1677 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1678 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1679 MoodleQuickForm
::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
1680 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1681 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1682 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1683 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1684 MoodleQuickForm
::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1685 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1686 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1687 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1688 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');