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.
20 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
23 if (!defined('MOODLE_INTERNAL')) {
24 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
28 //setup.php icludes our hacked pear libs first
29 require_once 'HTML/QuickForm.php';
30 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
31 require_once 'HTML/QuickForm/Renderer/Tableless.php';
33 require_once $CFG->libdir
.'/uploadlib.php';
36 * Callback called when PEAR throws an error
38 * @param PEAR_Error $error
40 function pear_handle_error($error){
41 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
42 echo '<br /> <strong>Backtrace </strong>:';
43 print_object($error->backtrace
);
46 if ($CFG->debug
>= DEBUG_ALL
){
47 PEAR
::setErrorHandling(PEAR_ERROR_CALLBACK
, 'pear_handle_error');
52 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
53 * use this class you should write a class definition which extends this class or a more specific
54 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
56 * You will write your own definition() method which performs the form set up.
59 var $_formname; // form name
61 * quickform object definition
63 * @var MoodleQuickForm
77 var $_upload_manager; //
79 * definition_after_data executed flag
80 * @var definition_finalized
82 var $_definition_finalized = false;
85 * The constructor function calls the abstract function definition() and it will then
86 * process and clean and attempt to validate incoming data.
88 * It will call your custom validate method to validate data and will also check any rules
89 * you have specified in definition using addRule
91 * The name of the form (id attribute of the form) is automatically generated depending on
92 * the name you gave the class extending moodleform. You should call your class something
95 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
96 * current url. If a moodle_url object then outputs params as hidden variables.
97 * @param array $customdata if your form defintion method needs access to data such as $course
98 * $cm, etc. to construct the form definition then pass it in this array. You can
99 * use globals for somethings.
100 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
101 * be merged and used as incoming data to the form.
102 * @param string $target target frame for form submission. You will rarely use this. Don't use
103 * it if you don't need to as the target attribute is deprecated in xhtml
105 * @param mixed $attributes you can pass a string of html attributes here or an array.
108 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
110 $action = strip_querystring(qualified_me());
113 $this->_formname
= get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
114 $this->_customdata
= $customdata;
115 $this->_form
=& new MoodleQuickForm($this->_formname
, $method, $action, $target, $attributes);
117 $this->_form
->hardFreeze();
119 $this->set_upload_manager(new upload_manager());
123 $this->_form
->addElement('hidden', 'sesskey', null); // automatic sesskey protection
124 $this->_form
->setType('sesskey', PARAM_RAW
);
125 $this->_form
->setDefault('sesskey', sesskey());
126 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
127 $this->_form
->setType('_qf__'.$this->_formname
, PARAM_RAW
);
128 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
129 $this->_form
->_setDefaultRuleMessages();
131 // we have to know all input types before processing submission ;-)
132 $this->_process_submission($method);
136 * To autofocus on first form element or first element with error.
138 * @param string $name if this is set then the focus is forced to a field with this name
140 * @return string javascript to select form element with first error or
141 * first element if no errors. Use this as a parameter
142 * when calling print_header
144 function focus($name=NULL) {
145 $form =& $this->_form
;
146 $elkeys = array_keys($form->_elementIndex
);
148 if (isset($form->_errors
) && 0 != count($form->_errors
)){
149 $errorkeys = array_keys($form->_errors
);
150 $elkeys = array_intersect($elkeys, $errorkeys);
154 if ($error or empty($name)) {
156 while (empty($names) and !empty($elkeys)) {
157 $el = array_shift($elkeys);
158 $names = $form->_getElNamesRecursive($el);
160 if (!empty($names)) {
161 $name = array_shift($names);
167 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
174 * Internal method. Alters submitted data to be suitable for quickforms processing.
175 * Must be called when the form is fully set up.
177 function _process_submission($method) {
178 $submission = array();
179 if ($method == 'post') {
180 if (!empty($_POST)) {
181 $submission = $_POST;
184 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
187 // following trick is needed to enable proper sesskey checks when using GET forms
188 // the _qf__.$this->_formname serves as a marker that form was actually submitted
189 if (array_key_exists('_qf__'.$this->_formname
, $submission) and $submission['_qf__'.$this->_formname
] == 1) {
190 if (!confirm_sesskey()) {
191 print_error('invalidsesskey');
195 $submission = array();
199 $this->_form
->updateSubmission($submission, $files);
203 * Internal method. Validates all uploaded files.
205 function _validate_files(&$files) {
208 if (empty($_FILES)) {
209 // we do not need to do any checks because no files were submitted
210 // note: server side rules do not work for files - use custom verification in validate() instead
214 $mform =& $this->_form
;
217 $status = $this->_upload_manager
->preprocess_files();
219 // now check that we really want each file
220 foreach ($_FILES as $elname=>$file) {
221 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
222 $required = $mform->isElementRequired($elname);
223 if (!empty($this->_upload_manager
->files
[$elname]['uploadlog']) and empty($this->_upload_manager
->files
[$elname]['clear'])) {
224 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE
) {
225 // file not uploaded and not required - ignore it
228 $errors[$elname] = $this->_upload_manager
->files
[$elname]['uploadlog'];
230 } else if (!empty($this->_upload_manager
->files
[$elname]['clear'])) {
231 $files[$elname] = $this->_upload_manager
->files
[$elname]['tmp_name'];
234 error('Incorrect upload attempt!');
238 // return errors if found
239 if ($status and 0 == count($errors)){
249 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
250 * form definition (new entry form); this function is used to load in data where values
251 * already exist and data is being edited (edit entry form).
253 * @param mixed $default_values object or array of default values
254 * @param bool $slased true if magic quotes applied to data values
256 function set_data($default_values, $slashed=false) {
257 if (is_object($default_values)) {
258 $default_values = (array)$default_values;
260 $filter = $slashed ?
'stripslashes' : NULL;
261 $this->_form
->setDefaults($default_values, $filter);
265 * Set custom upload manager.
266 * Must be used BEFORE creating of file element!
268 * @param object $um - custom upload manager
270 function set_upload_manager($um=false) {
272 $um = new upload_manager();
274 $this->_upload_manager
= $um;
276 $this->_form
->setMaxFileSize($um->config
->maxbytes
);
280 * Check that form was submitted. Does not check validity of submitted data.
282 * @return bool true if form properly submitted
284 function is_submitted() {
285 return $this->_form
->isSubmitted();
288 function no_submit_button_pressed(){
289 static $nosubmit = null; // one check is enough
290 if (!is_null($nosubmit)){
293 $mform =& $this->_form
;
295 if (!$this->is_submitted()){
298 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
299 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
309 * Check that form data is valid.
310 * You should almost always use this, rather than {@see validate_defined_fields}
312 * @return bool true if form data valid
314 function is_validated() {
315 //finalize the form definition before any processing
316 if (!$this->_definition_finalized
) {
317 $this->_definition_finalized
= true;
318 $this->definition_after_data();
320 return $this->validate_defined_fields();
326 * You almost always want to call {@see is_validated} instead of this
327 * because it calls {@see definition_after_data} first, before validating the form,
328 * which is what you want in 99% of cases.
330 * This is provided as a separate function for those special cases where
331 * you want the form validated before definition_after_data is called
332 * for example, to selectively add new elements depending on a no_submit_button press,
333 * but only when the form is valid when the no_submit_button is pressed,
335 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
336 * is NOT to validate the form when a no submit button has been pressed.
337 * pass true here to override this behaviour
339 * @return bool true if form data valid
341 function validate_defined_fields($validateonnosubmit=false) {
342 static $validated = null; // one validation is enough
343 $mform =& $this->_form
;
345 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
347 } elseif ($validated === null) {
348 $internal_val = $mform->validate();
351 $file_val = $this->_validate_files($files);
352 if ($file_val !== true) {
353 if (!empty($file_val)) {
354 foreach ($file_val as $element=>$msg) {
355 $mform->setElementError($element, $msg);
361 $data = $mform->exportValues(null, true);
362 $moodle_val = $this->validation($data, $files);
363 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
364 // non-empty array means errors
365 foreach ($moodle_val as $element=>$msg) {
366 $mform->setElementError($element, $msg);
371 // anything else means validation ok
375 $validated = ($internal_val and $moodle_val and $file_val);
381 * Return true if a cancel button has been pressed resulting in the form being submitted.
383 * @return boolean true if a cancel button has been pressed
385 function is_cancelled(){
386 $mform =& $this->_form
;
387 if ($mform->isSubmitted()){
388 foreach ($mform->_cancelButtons
as $cancelbutton){
389 if (optional_param($cancelbutton, 0, PARAM_RAW
)){
398 * Return submitted data if properly submitted or returns NULL if validation fails or
399 * if there is no submitted data.
401 * @param bool $slashed true means return data with addslashes applied
402 * @return object submitted data; NULL if not valid or not submitted
404 function get_data($slashed=true) {
405 $mform =& $this->_form
;
407 if ($this->is_submitted() and $this->is_validated()) {
408 $data = $mform->exportValues(null, $slashed);
409 unset($data['sesskey']); // we do not need to return sesskey
410 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
414 return (object)$data;
422 * Return submitted data without validation or NULL if there is no submitted data.
424 * @param bool $slashed true means return data with addslashes applied
425 * @return object submitted data; NULL if not submitted
427 function get_submitted_data($slashed=true) {
428 $mform =& $this->_form
;
430 if ($this->is_submitted()) {
431 $data = $mform->exportValues(null, $slashed);
432 unset($data['sesskey']); // we do not need to return sesskey
433 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
437 return (object)$data;
445 * Save verified uploaded files into directory. Upload process can be customised from definition()
446 * method by creating instance of upload manager and storing it in $this->_upload_form
448 * @param string $destination where to store uploaded files
449 * @return bool success
451 function save_files($destination) {
452 if ($this->is_submitted() and $this->is_validated()) {
453 return $this->_upload_manager
->save_files($destination);
459 * If we're only handling one file (if inputname was given in the constructor)
460 * this will return the (possibly changed) filename of the file.
461 * @return mixed false in case of failure, string if ok
463 function get_new_filename() {
464 return $this->_upload_manager
->get_new_filename();
468 * Get content of uploaded file.
469 * @param $element name of file upload element
470 * @return mixed false in case of failure, string if ok
472 function get_file_content($elname) {
473 if (!$this->is_submitted() or !$this->is_validated()) {
477 if (!$this->_form
->elementExists($elname)) {
481 if (empty($this->_upload_manager
->files
[$elname]['clear'])) {
485 if (empty($this->_upload_manager
->files
[$elname]['tmp_name'])) {
490 $file = @fopen
($this->_upload_manager
->files
[$elname]['tmp_name'], "rb");
492 while (!feof($file)) {
493 $data .= fread($file, 1024); // TODO: do we really have to do this?
506 //finalize the form definition if not yet done
507 if (!$this->_definition_finalized
) {
508 $this->_definition_finalized
= true;
509 $this->definition_after_data();
511 $this->_form
->display();
515 * Abstract method - always override!
517 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
519 function definition() {
520 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
524 * Dummy stub method - override if you need to setup the form depending on current
525 * values. This method is called after definition(), data submission and set_data().
526 * All form setup that is dependent on form values should go in here.
528 function definition_after_data(){
532 * Dummy stub method - override if you needed to perform some extra validation.
533 * If there are errors return array of errors ("fieldname"=>"error message"),
534 * otherwise true if ok.
536 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
538 * @param array $data array of ("fieldname"=>value) of submitted data
539 * @param array $files array of uploaded files "element_name"=>tmp_file_path
540 * @return array of "element_name"=>"error_description" if there are errors,
541 * or an empty array if everything is OK (true allowed for backwards compatibility too).
543 function validation($data, $files) {
548 * Method to add a repeating group of elements to a form.
550 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
551 * @param integer $repeats no of times to repeat elements initially
552 * @param array $options Array of options to apply to elements. Array keys are element names.
553 * This is an array of arrays. The second sets of keys are the option types
555 * 'default' - default value is value
556 * 'type' - PARAM_* constant is value
557 * 'helpbutton' - helpbutton params array is value
558 * 'disabledif' - last three moodleform::disabledIf()
559 * params are value as an array
560 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
561 * @param string $addfieldsname name for button to add more fields
562 * @param int $addfieldsno how many fields to add at a time
563 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
564 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
565 * @return int no of repeats of element in this page
567 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
568 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
569 if ($addstring===null){
570 $addstring = get_string('addfields', 'form', $addfieldsno);
572 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
574 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT
);
575 $addfields = optional_param($addfieldsname, '', PARAM_TEXT
);
576 if (!empty($addfields)){
577 $repeats +
= $addfieldsno;
579 $mform =& $this->_form
;
580 $mform->registerNoSubmitButton($addfieldsname);
581 $mform->addElement('hidden', $repeathiddenname, $repeats);
582 $mform->setType($repeathiddenname, PARAM_INT
);
583 //value not to be overridden by submitted value
584 $mform->setConstants(array($repeathiddenname=>$repeats));
585 $namecloned = array();
586 for ($i = 0; $i < $repeats; $i++
) {
587 foreach ($elementobjs as $elementobj){
588 $elementclone = fullclone($elementobj);
589 $name = $elementclone->getName();
590 $namecloned[] = $name;
592 $elementclone->setName($name."[$i]");
594 if (is_a($elementclone, 'HTML_QuickForm_header')) {
595 $value = $elementclone->_text
;
596 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
599 $value=$elementclone->getLabel();
600 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
604 $mform->addElement($elementclone);
607 for ($i=0; $i<$repeats; $i++
) {
608 foreach ($options as $elementname => $elementoptions){
609 $pos=strpos($elementname, '[');
611 $realelementname = substr($elementname, 0, $pos+
1)."[$i]";
612 $realelementname .= substr($elementname, $pos+
1);
614 $realelementname = $elementname."[$i]";
616 foreach ($elementoptions as $option => $params){
620 $mform->setDefault($realelementname, $params);
623 $mform->setHelpButton($realelementname, $params);
626 foreach ($namecloned as $num => $name){
627 if ($params[0] == $name){
628 $params[0] = $params[0]."[$i]";
632 $params = array_merge(array($realelementname), $params);
633 call_user_func_array(array(&$mform, 'disabledIf'), $params);
636 if (is_string($params)){
637 $params = array(null, $params, null, 'client');
639 $params = array_merge(array($realelementname), $params);
640 call_user_func_array(array(&$mform, 'addRule'), $params);
647 $mform->addElement('submit', $addfieldsname, $addstring);
649 if (!$addbuttoninside) {
650 $mform->closeHeaderBefore($addfieldsname);
657 * Adds a link/button that controls the checked state of a group of checkboxes.
658 * @param int $groupid The id of the group of advcheckboxes this element controls
659 * @param string $text The text of the link. Defaults to "select all/none"
660 * @param array $attributes associative array of HTML attributes
661 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
663 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
666 $text = get_string('selectallornone', 'form');
669 $mform = $this->_form
;
670 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT
);
672 if ($select_value == 0 ||
is_null($select_value)) {
673 $new_select_value = 1;
675 $new_select_value = 0;
678 $mform->addElement('hidden', "checkbox_controller$groupid");
679 $mform->setType("checkbox_controller$groupid", PARAM_INT
);
680 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
682 // Locate all checkboxes for this group and set their value, IF the optional param was given
683 if (!is_null($select_value)) {
684 foreach ($this->_form
->_elements
as $element) {
685 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
686 $mform->setConstants(array($element->getAttribute('name') => $select_value));
691 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
692 $mform->registerNoSubmitButton($checkbox_controller_name);
694 // Prepare Javascript for submit element
695 $js = "\n//<![CDATA[\n";
696 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
698 function html_quickform_toggle_checkboxes(group) {
699 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
700 var newvalue = false;
701 var global = eval('html_quickform_checkboxgroup' + group + ';');
703 eval('html_quickform_checkboxgroup' + group + ' = 0;');
706 eval('html_quickform_checkboxgroup' + group + ' = 1;');
707 newvalue = 'checked';
710 for (i = 0; i < checkboxes.length; i++) {
711 checkboxes[i].checked = newvalue;
715 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
717 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
721 require_once("$CFG->libdir/form/submitlink.php");
722 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
723 $submitlink->_js
= $js;
724 $submitlink->_onclick
= "html_quickform_toggle_checkboxes($groupid); return false;";
725 $mform->addElement($submitlink);
726 $mform->setDefault($checkbox_controller_name, $text);
730 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
731 * if you don't want a cancel button in your form. If you have a cancel button make sure you
732 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
733 * get data with get_data().
735 * @param boolean $cancel whether to show cancel button, default true
736 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
738 function add_action_buttons($cancel = true, $submitlabel=null){
739 if (is_null($submitlabel)){
740 $submitlabel = get_string('savechanges');
742 $mform =& $this->_form
;
744 //when two elements we need a group
745 $buttonarray=array();
746 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
747 $buttonarray[] = &$mform->createElement('cancel');
748 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
749 $mform->closeHeaderBefore('buttonar');
752 $mform->addElement('submit', 'submitbutton', $submitlabel);
753 $mform->closeHeaderBefore('submitbutton');
759 * You never extend this class directly. The class methods of this class are available from
760 * the private $this->_form property on moodleform and its children. You generally only
761 * call methods on this class from within abstract methods that you override on moodleform such
762 * as definition and definition_after_data
765 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
766 var $_types = array();
767 var $_dependencies = array();
769 * Array of buttons that if pressed do not result in the processing of the form.
773 var $_noSubmitButtons=array();
775 * Array of buttons that if pressed do not result in the processing of the form.
779 var $_cancelButtons=array();
782 * Array whose keys are element names. If the key exists this is a advanced element
786 var $_advancedElements = array();
789 * Whether to display advanced elements (on page load)
793 var $_showAdvanced = null;
796 * The form name is derrived from the class name of the wrapper minus the trailing form
797 * It is a name with words joined by underscores whereas the id attribute is words joined by
805 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
809 var $_pageparams = '';
812 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
813 * @param string $formName Form's name.
814 * @param string $method (optional)Form's method defaults to 'POST'
815 * @param mixed $action (optional)Form's action - string or moodle_url
816 * @param string $target (optional)Form's target defaults to none
817 * @param mixed $attributes (optional)Extra attributes for <form> tag
818 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
821 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
824 static $formcounter = 1;
826 HTML_Common
::HTML_Common($attributes);
827 $target = empty($target) ?
array() : array('target' => $target);
828 $this->_formName
= $formName;
829 if (is_a($action, 'moodle_url')){
830 $this->_pageparams
= $action->hidden_params_out();
831 $action = $action->out(true);
833 $this->_pageparams
= '';
835 //no 'name' atttribute for form in xhtml strict :
836 $attributes = array('action'=>$action, 'method'=>$method,
837 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) +
$target;
839 $this->updateAttributes($attributes);
841 //this is custom stuff for Moodle :
842 $oldclass= $this->getAttribute('class');
843 if (!empty($oldclass)){
844 $this->updateAttributes(array('class'=>$oldclass.' mform'));
846 $this->updateAttributes(array('class'=>'mform'));
848 $this->_reqHTML
= '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />';
849 $this->_advancedHTML
= '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath
.'/adv.gif'.'" />';
850 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />'));
851 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
855 * Use this method to indicate an element in a form is an advanced field. If items in a form
856 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
857 * form so the user can decide whether to display advanced form controls.
859 * If you set a header element to advanced then all elements it contains will also be set as advanced.
861 * @param string $elementName group or element name (not the element name of something inside a group).
862 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
864 function setAdvanced($elementName, $advanced=true){
866 $this->_advancedElements
[$elementName]='';
867 } elseif (isset($this->_advancedElements
[$elementName])) {
868 unset($this->_advancedElements
[$elementName]);
870 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
871 $this->setShowAdvanced();
872 $this->registerNoSubmitButton('mform_showadvanced');
874 $this->addElement('hidden', 'mform_showadvanced_last');
875 $this->setType('mform_showadvanced_last', PARAM_INT
);
879 * Set whether to show advanced elements in the form on first displaying form. Default is not to
880 * display advanced elements in the form until 'Show Advanced' is pressed.
882 * You can get the last state of the form and possibly save it for this user by using
883 * value 'mform_showadvanced_last' in submitted data.
885 * @param boolean $showadvancedNow
887 function setShowAdvanced($showadvancedNow = null){
888 if ($showadvancedNow === null){
889 if ($this->_showAdvanced
!== null){
891 } else { //if setShowAdvanced is called without any preference
892 //make the default to not show advanced elements.
893 $showadvancedNow = get_user_preferences(
894 moodle_strtolower($this->_formName
.'_showadvanced', 0));
897 //value of hidden element
898 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT
);
900 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW
);
901 //toggle if button pressed or else stay the same
902 if ($hiddenLast == -1) {
903 $next = $showadvancedNow;
904 } elseif ($buttonPressed) { //toggle on button press
905 $next = !$hiddenLast;
909 $this->_showAdvanced
= $next;
910 if ($showadvancedNow != $next){
911 set_user_preference($this->_formName
.'_showadvanced', $next);
913 $this->setConstants(array('mform_showadvanced_last'=>$next));
915 function getShowAdvanced(){
916 return $this->_showAdvanced
;
923 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
928 function accept(&$renderer) {
929 if (method_exists($renderer, 'setAdvancedElements')){
930 //check for visible fieldsets where all elements are advanced
931 //and mark these headers as advanced as well.
932 //And mark all elements in a advanced header as advanced
933 $stopFields = $renderer->getStopFieldSetElements();
935 $lastHeaderAdvanced = false;
936 $anyAdvanced = false;
937 foreach (array_keys($this->_elements
) as $elementIndex){
938 $element =& $this->_elements
[$elementIndex];
940 // if closing header and any contained element was advanced then mark it as advanced
941 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
942 if ($anyAdvanced && !is_null($lastHeader)){
943 $this->setAdvanced($lastHeader->getName());
945 $lastHeaderAdvanced = false;
948 } elseif ($lastHeaderAdvanced) {
949 $this->setAdvanced($element->getName());
952 if ($element->getType()=='header'){
953 $lastHeader =& $element;
954 $anyAdvanced = false;
955 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
956 } elseif (isset($this->_advancedElements
[$element->getName()])){
960 // the last header may not be closed yet...
961 if ($anyAdvanced && !is_null($lastHeader)){
962 $this->setAdvanced($lastHeader->getName());
964 $renderer->setAdvancedElements($this->_advancedElements
);
967 parent
::accept($renderer);
972 function closeHeaderBefore($elementName){
973 $renderer =& $this->defaultRenderer();
974 $renderer->addStopFieldsetElements($elementName);
978 * Should be used for all elements of a form except for select, radio and checkboxes which
979 * clean their own data.
981 * @param string $elementname
982 * @param integer $paramtype use the constants PARAM_*.
983 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
984 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
985 * It will strip all html tags. But will still let tags for multilang support
987 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
988 * html editor. Data from the editor is later cleaned before display using
989 * format_text() function. PARAM_RAW can also be used for data that is validated
990 * by some other way or printed by p() or s().
991 * * PARAM_INT should be used for integers.
992 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
995 function setType($elementname, $paramtype) {
996 $this->_types
[$elementname] = $paramtype;
1000 * See description of setType above. This can be used to set several types at once.
1002 * @param array $paramtypes
1004 function setTypes($paramtypes) {
1005 $this->_types
= $paramtypes +
$this->_types
;
1008 function updateSubmission($submission, $files) {
1009 $this->_flagSubmitted
= false;
1011 if (empty($submission)) {
1012 $this->_submitValues
= array();
1014 foreach ($submission as $key=>$s) {
1015 if (array_key_exists($key, $this->_types
)) {
1016 $submission[$key] = clean_param($s, $this->_types
[$key]);
1019 $this->_submitValues
= $this->_recursiveFilter('stripslashes', $submission);
1020 $this->_flagSubmitted
= true;
1023 if (empty($files)) {
1024 $this->_submitFiles
= array();
1026 if (1 == get_magic_quotes_gpc()) {
1027 foreach (array_keys($files) as $elname) {
1028 // dangerous characters in filenames are cleaned later in upload_manager
1029 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
1032 $this->_submitFiles
= $files;
1033 $this->_flagSubmitted
= true;
1036 // need to tell all elements that they need to update their value attribute.
1037 foreach (array_keys($this->_elements
) as $key) {
1038 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
1042 function getReqHTML(){
1043 return $this->_reqHTML
;
1046 function getAdvancedHTML(){
1047 return $this->_advancedHTML
;
1051 * Initializes a default form value. Used to specify the default for a new entry where
1052 * no data is loaded in using moodleform::set_data()
1054 * @param string $elementname element name
1055 * @param mixed $values values for that element name
1056 * @param bool $slashed the default value is slashed
1060 function setDefault($elementName, $defaultValue, $slashed=false){
1061 $filter = $slashed ?
'stripslashes' : NULL;
1062 $this->setDefaults(array($elementName=>$defaultValue), $filter);
1063 } // end func setDefault
1065 * Add an array of buttons to the form
1066 * @param array $buttons An associative array representing help button to attach to
1067 * to the form. keys of array correspond to names of elements in form.
1071 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1073 foreach ($buttons as $elementname => $button){
1074 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1078 * Add a single button.
1080 * @param string $elementname name of the element to add the item to
1081 * @param array $button - arguments to pass to function $function
1082 * @param boolean $suppresscheck - whether to throw an error if the element
1084 * @param string $function - function to generate html from the arguments in $button
1086 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
1087 if (array_key_exists($elementname, $this->_elementIndex
)){
1088 //_elements has a numeric index, this code accesses the elements by name
1089 $element=&$this->_elements
[$this->_elementIndex
[$elementname]];
1090 if (method_exists($element, 'setHelpButton')){
1091 $element->setHelpButton($button, $function);
1094 $a->name
=$element->getName();
1095 $a->classname
=get_class($element);
1096 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
1098 }elseif (!$suppresscheck){
1099 print_error('nonexistentformelements', 'form', '', $elementname);
1104 * Set constant value not overriden by _POST or _GET
1105 * note: this does not work for complex names with [] :-(
1106 * @param string $elname name of element
1107 * @param mixed $value
1110 function setConstant($elname, $value) {
1111 $this->_constantValues
= HTML_QuickForm
::arrayMerge($this->_constantValues
, array($elname=>$value));
1112 $element =& $this->getElement($elname);
1113 $element->onQuickFormEvent('updateValue', null, $this);
1116 function exportValues($elementList= null, $addslashes=true){
1117 $unfiltered = array();
1118 if (null === $elementList) {
1119 // iterate over all elements, calling their exportValue() methods
1120 $emptyarray = array();
1121 foreach (array_keys($this->_elements
) as $key) {
1122 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
){
1123 $value = $this->_elements
[$key]->exportValue($emptyarray, true);
1125 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
1128 if (is_array($value)) {
1129 // This shit throws a bogus warning in PHP 4.3.x
1130 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
1134 if (!is_array($elementList)) {
1135 $elementList = array_map('trim', explode(',', $elementList));
1137 foreach ($elementList as $elementName) {
1138 $value = $this->exportValue($elementName);
1139 if (PEAR
::isError($value)) {
1142 $unfiltered[$elementName] = $value;
1147 return $this->_recursiveFilter('addslashes', $unfiltered);
1153 * Adds a validation rule for the given field
1155 * If the element is in fact a group, it will be considered as a whole.
1156 * To validate grouped elements as separated entities,
1157 * use addGroupRule instead of addRule.
1159 * @param string $element Form element name
1160 * @param string $message Message to display for invalid data
1161 * @param string $type Rule type, use getRegisteredRules() to get types
1162 * @param string $format (optional)Required for extra rule data
1163 * @param string $validation (optional)Where to perform validation: "server", "client"
1164 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1165 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1168 * @throws HTML_QuickForm_Error
1170 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1172 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
1173 if ($validation == 'client') {
1174 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1177 } // end func addRule
1179 * Adds a validation rule for the given group of elements
1181 * Only groups with a name can be assigned a validation rule
1182 * Use addGroupRule when you need to validate elements inside the group.
1183 * Use addRule if you need to validate the group as a whole. In this case,
1184 * the same rule will be applied to all elements in the group.
1185 * Use addRule if you need to validate the group against a function.
1187 * @param string $group Form group name
1188 * @param mixed $arg1 Array for multiple elements or error message string for one element
1189 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1190 * @param string $format (optional)Required for extra rule data
1191 * @param int $howmany (optional)How many valid elements should be in the group
1192 * @param string $validation (optional)Where to perform validation: "server", "client"
1193 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1196 * @throws HTML_QuickForm_Error
1198 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1200 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1201 if (is_array($arg1)) {
1202 foreach ($arg1 as $rules) {
1203 foreach ($rules as $rule) {
1204 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
1206 if ('client' == $validation) {
1207 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1211 } elseif (is_string($arg1)) {
1213 if ($validation == 'client') {
1214 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1217 } // end func addGroupRule
1221 * Returns the client side validation script
1223 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1224 * and slightly modified to run rules per-element
1225 * Needed to override this because of an error with client side validation of grouped elements.
1228 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1230 function getValidationScript()
1232 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1236 include_once('HTML/QuickForm/RuleRegistry.php');
1237 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1248 foreach ($this->_rules
as $elementName => $rules) {
1249 foreach ($rules as $rule) {
1250 if ('client' == $rule['validation']) {
1251 unset($element); //TODO: find out how to properly initialize it
1253 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1254 $rule['message'] = strtr($rule['message'], $js_escape);
1256 if (isset($rule['group'])) {
1257 $group =& $this->getElement($rule['group']);
1258 // No JavaScript validation for frozen elements
1259 if ($group->isFrozen()) {
1262 $elements =& $group->getElements();
1263 foreach (array_keys($elements) as $key) {
1264 if ($elementName == $group->getElementName($key)) {
1265 $element =& $elements[$key];
1269 } elseif ($dependent) {
1271 $element[] =& $this->getElement($elementName);
1272 foreach ($rule['dependent'] as $elName) {
1273 $element[] =& $this->getElement($elName);
1276 $element =& $this->getElement($elementName);
1278 // No JavaScript validation for frozen elements
1279 if (is_object($element) && $element->isFrozen()) {
1281 } elseif (is_array($element)) {
1282 foreach (array_keys($element) as $key) {
1283 if ($element[$key]->isFrozen()) {
1288 // Fix for bug displaying errors for elements in a group
1289 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1290 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1291 $test[$elementName][1]=$element;
1297 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1298 // the form, and then that form field gets corrupted by the code that follows.
1302 <script type="text/javascript">
1305 var skipClientValidation = false;
1307 function qf_errorHandler(element, _qfMsg) {
1308 div = element.parentNode;
1309 if (_qfMsg != \'\') {
1310 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1312 errorSpan = document.createElement("span");
1313 errorSpan.id = \'id_error_\'+element.name;
1314 errorSpan.className = "error";
1315 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1318 while (errorSpan.firstChild) {
1319 errorSpan.removeChild(errorSpan.firstChild);
1322 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1323 errorSpan.appendChild(document.createElement("br"));
1325 if (div.className.substr(div.className.length - 6, 6) != " error"
1326 && div.className != "error") {
1327 div.className += " error";
1332 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1334 errorSpan.parentNode.removeChild(errorSpan);
1337 if (div.className.substr(div.className.length - 6, 6) == " error") {
1338 div.className = div.className.substr(0, div.className.length - 6);
1339 } else if (div.className == "error") {
1347 foreach ($test as $elementName => $jsandelement) {
1348 // Fix for bug displaying errors for elements in a group
1350 list($jsArr,$element)=$jsandelement;
1353 function validate_' . $this->_formName
. '_' . $elementName . '(element) {
1355 var errFlag = new Array();
1358 var frm = element.parentNode;
1359 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1360 frm = frm.parentNode;
1362 ' . join("\n", $jsArr) . '
1363 return qf_errorHandler(element, _qfMsg);
1367 ret = validate_' . $this->_formName
. '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1368 if (!ret && !first_focus) {
1370 frm.elements[\''.$elementName.'\'].focus();
1374 // Fix for bug displaying errors for elements in a group
1376 //$element =& $this->getElement($elementName);
1378 $valFunc = 'validate_' . $this->_formName
. '_' . $elementName . '(this)';
1379 $onBlur = $element->getAttribute('onBlur');
1380 $onChange = $element->getAttribute('onChange');
1381 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1382 'onChange' => $onChange . $valFunc));
1384 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1386 function validate_' . $this->_formName
. '(frm) {
1387 if (skipClientValidation) {
1392 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1393 var first_focus = false;
1394 ' . $validateJS . ';
1400 } // end func getValidationScript
1401 function _setDefaultRuleMessages(){
1402 foreach ($this->_rules
as $field => $rulesarr){
1403 foreach ($rulesarr as $key => $rule){
1404 if ($rule['message']===null){
1406 $a->format
=$rule['format'];
1407 $str=get_string('err_'.$rule['type'], 'form', $a);
1408 if (strpos($str, '[[')!==0){
1409 $this->_rules
[$field][$key]['message']=$str;
1416 function getLockOptionEndScript(){
1418 $iname = $this->getAttribute('id').'items';
1419 $js = '<script type="text/javascript">'."\n";
1420 $js .= '//<![CDATA['."\n";
1421 $js .= "var $iname = Array();\n";
1423 foreach ($this->_dependencies
as $dependentOn => $conditions){
1424 $js .= "{$iname}['$dependentOn'] = Array();\n";
1425 foreach ($conditions as $condition=>$values) {
1426 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1427 foreach ($values as $value=>$dependents) {
1428 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1430 foreach ($dependents as $dependent) {
1431 $elements = $this->_getElNamesRecursive($dependent);
1432 if (empty($elements)) {
1433 // probably element inside of some group
1434 $elements = array($dependent);
1436 foreach($elements as $element) {
1437 if ($element == $dependentOn) {
1440 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1447 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1449 $js .='</script>'."\n";
1453 function _getElNamesRecursive($element) {
1454 if (is_string($element)) {
1455 if (!$this->elementExists($element)) {
1458 $element = $this->getElement($element);
1461 if (is_a($element, 'HTML_QuickForm_group')) {
1462 $elsInGroup = $element->getElements();
1464 foreach ($elsInGroup as $elInGroup){
1465 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1466 // not sure if this would work - groups nested in groups
1467 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1469 $elNames[] = $element->getElementName($elInGroup->getName());
1473 } else if (is_a($element, 'HTML_QuickForm_header')) {
1476 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1479 } else if (method_exists($element, 'getPrivateName')) {
1480 return array($element->getPrivateName());
1483 $elNames = array($element->getName());
1490 * Adds a dependency for $elementName which will be disabled if $condition is met.
1491 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1492 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1493 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1494 * of the $dependentOn element is $condition (such as equal) to $value.
1496 * @param string $elementName the name of the element which will be disabled
1497 * @param string $dependentOn the name of the element whose state will be checked for
1499 * @param string $condition the condition to check
1500 * @param mixed $value used in conjunction with condition.
1502 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1503 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
1504 $this->_dependencies
[$dependentOn] = array();
1506 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
1507 $this->_dependencies
[$dependentOn][$condition] = array();
1509 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
1510 $this->_dependencies
[$dependentOn][$condition][$value] = array();
1512 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
1515 function registerNoSubmitButton($buttonname){
1516 $this->_noSubmitButtons
[]=$buttonname;
1519 function isNoSubmitButton($buttonname){
1520 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
1523 function _registerCancelButton($addfieldsname){
1524 $this->_cancelButtons
[]=$addfieldsname;
1527 * Displays elements without HTML input tags.
1528 * This method is different to freeze() in that it makes sure no hidden
1529 * elements are included in the form.
1530 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1532 * This function also removes all previously defined rules.
1534 * @param mixed $elementList array or string of element(s) to be frozen
1537 * @throws HTML_QuickForm_Error
1539 function hardFreeze($elementList=null)
1541 if (!isset($elementList)) {
1542 $this->_freezeAll
= true;
1543 $elementList = array();
1545 if (!is_array($elementList)) {
1546 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1548 $elementList = array_flip($elementList);
1551 foreach (array_keys($this->_elements
) as $key) {
1552 $name = $this->_elements
[$key]->getName();
1553 if ($this->_freezeAll ||
isset($elementList[$name])) {
1554 $this->_elements
[$key]->freeze();
1555 $this->_elements
[$key]->setPersistantFreeze(false);
1556 unset($elementList[$name]);
1559 $this->_rules
[$name] = array();
1560 // if field is required, remove the rule
1561 $unset = array_search($name, $this->_required
);
1562 if ($unset !== false) {
1563 unset($this->_required
[$unset]);
1568 if (!empty($elementList)) {
1569 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);
1574 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1576 * This function also removes all previously defined rules of elements it freezes.
1578 * @param array $elementList array or string of element(s) not to be frozen
1581 * @throws HTML_QuickForm_Error
1583 function hardFreezeAllVisibleExcept($elementList)
1585 $elementList = array_flip($elementList);
1586 foreach (array_keys($this->_elements
) as $key) {
1587 $name = $this->_elements
[$key]->getName();
1588 $type = $this->_elements
[$key]->getType();
1590 if ($type == 'hidden'){
1591 // leave hidden types as they are
1592 } elseif (!isset($elementList[$name])) {
1593 $this->_elements
[$key]->freeze();
1594 $this->_elements
[$key]->setPersistantFreeze(false);
1597 $this->_rules
[$name] = array();
1598 // if field is required, remove the rule
1599 $unset = array_search($name, $this->_required
);
1600 if ($unset !== false) {
1601 unset($this->_required
[$unset]);
1608 * Tells whether the form was already submitted
1610 * This is useful since the _submitFiles and _submitValues arrays
1611 * may be completely empty after the trackSubmit value is removed.
1616 function isSubmitted()
1618 return parent
::isSubmitted() && (!$this->isFrozen());
1624 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1625 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1627 * Stylesheet is part of standard theme and should be automatically included.
1629 * @author Jamie Pratt <me@jamiep.org>
1630 * @license gpl license
1632 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
1635 * Element template array
1639 var $_elementTemplates;
1641 * Template used when opening a hidden fieldset
1642 * (i.e. a fieldset that is opened when there is no header element)
1646 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1648 * Header Template string
1652 var $_headerTemplate =
1653 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1656 * Template used when opening a fieldset
1660 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1663 * Template used when closing a fieldset
1667 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1670 * Required Note template string
1674 var $_requiredNoteTemplate =
1675 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1677 var $_advancedElements = array();
1680 * Whether to display advanced elements (on page load)
1682 * @var integer 1 means show 0 means hide
1686 function MoodleQuickForm_Renderer(){
1687 // switch next two lines for ol li containers for form items.
1688 // $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>');
1689 $this->_elementTemplates
= array(
1690 '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>',
1692 '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>',
1694 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element} </div></div>',
1698 parent
::HTML_QuickForm_Renderer_Tableless();
1701 function setAdvancedElements($elements){
1702 $this->_advancedElements
= $elements;
1706 * What to do when starting the form
1708 * @param MoodleQuickForm $form
1710 function startForm(&$form){
1711 $this->_reqHTML
= $form->getReqHTML();
1712 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
1713 $this->_advancedHTML
= $form->getAdvancedHTML();
1714 $this->_showAdvanced
= $form->getShowAdvanced();
1715 parent
::startForm($form);
1716 if ($form->isFrozen()){
1717 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
1719 $this->_hiddenHtml
.= $form->_pageparams
;
1725 function startGroup(&$group, $required, $error){
1726 if (method_exists($group, 'getElementTemplateType')){
1727 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
1729 $html = $this->_elementTemplates
['default'];
1732 if ($this->_showAdvanced
){
1733 $advclass = ' advanced';
1735 $advclass = ' advanced hide';
1737 if (isset($this->_advancedElements
[$group->getName()])){
1738 $html =str_replace(' {advanced}', $advclass, $html);
1739 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1741 $html =str_replace(' {advanced}', '', $html);
1742 $html =str_replace('{advancedimg}', '', $html);
1744 if (method_exists($group, 'getHelpButton')){
1745 $html =str_replace('{help}', $group->getHelpButton(), $html);
1747 $html =str_replace('{help}', '', $html);
1749 $html =str_replace('{name}', $group->getName(), $html);
1750 $html =str_replace('{type}', 'fgroup', $html);
1752 $this->_templates
[$group->getName()]=$html;
1753 // Fix for bug in tableless quickforms that didn't allow you to stop a
1754 // fieldset before a group of elements.
1755 // if the element name indicates the end of a fieldset, close the fieldset
1756 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
1757 && $this->_fieldsetsOpen
> 0
1759 $this->_html
.= $this->_closeFieldsetTemplate
;
1760 $this->_fieldsetsOpen
--;
1762 parent
::startGroup($group, $required, $error);
1765 function renderElement(&$element, $required, $error){
1766 //manipulate id of all elements before rendering
1767 if (!is_null($element->getAttribute('id'))) {
1768 $id = $element->getAttribute('id');
1770 $id = $element->getName();
1772 //strip qf_ prefix and replace '[' with '_' and strip ']'
1773 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1774 if (strpos($id, 'id_') !== 0){
1775 $element->updateAttributes(array('id'=>'id_'.$id));
1778 //adding stuff to place holders in template
1779 if (method_exists($element, 'getElementTemplateType')){
1780 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
1782 $html = $this->_elementTemplates
['default'];
1784 if ($this->_showAdvanced
){
1785 $advclass = ' advanced';
1787 $advclass = ' advanced hide';
1789 if (isset($this->_advancedElements
[$element->getName()])){
1790 $html =str_replace(' {advanced}', $advclass, $html);
1792 $html =str_replace(' {advanced}', '', $html);
1794 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
1795 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1797 $html =str_replace('{advancedimg}', '', $html);
1799 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1800 $html =str_replace('{name}', $element->getName(), $html);
1801 if (method_exists($element, 'getHelpButton')){
1802 $html = str_replace('{help}', $element->getHelpButton(), $html);
1804 $html = str_replace('{help}', '', $html);
1807 if (!isset($this->_templates
[$element->getName()])) {
1808 $this->_templates
[$element->getName()] = $html;
1811 parent
::renderElement($element, $required, $error);
1814 function finishForm(&$form){
1815 if ($form->isFrozen()){
1816 $this->_hiddenHtml
= '';
1818 parent
::finishForm($form);
1819 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1820 // add a lockoptions script
1821 $this->_html
= $this->_html
. "\n" . $script;
1825 * Called when visiting a header element
1827 * @param object An HTML_QuickForm_header element being visited
1831 function renderHeader(&$header) {
1832 $name = $header->getName();
1834 $id = empty($name) ?
'' : ' id="' . $name . '"';
1835 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1836 if (is_null($header->_text
)) {
1838 } elseif (!empty($name) && isset($this->_templates
[$name])) {
1839 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
1841 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
1844 if (isset($this->_advancedElements
[$name])){
1845 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
1847 $header_html =str_replace('{advancedimg}', '', $header_html);
1849 $elementName='mform_showadvanced';
1850 if ($this->_showAdvanced
==0){
1851 $buttonlabel = get_string('showadvanced', 'form');
1853 $buttonlabel = get_string('hideadvanced', 'form');
1856 if (isset($this->_advancedElements
[$name])){
1857 require_js(array('yui_yahoo', 'yui_event'));
1858 // this is tricky - the first submit button on form is "clicked" if user presses enter
1859 // we do not want to "submit" using advanced button if javascript active
1860 $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />';
1862 $buttonlabel = addslashes_js($buttonlabel);
1863 $showtext = addslashes_js(get_string('showadvanced', 'form'));
1864 $hidetext = addslashes_js(get_string('hideadvanced', 'form'));
1865 $button = '<script id="' . $name . '_script" type="text/javascript">' . "
1866 showAdvancedInit('{$name}_script', '$elementName', '$buttonlabel', '$hidetext', '$showtext');
1867 " . '</script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation
1869 $header_html = str_replace('{button}', $button, $header_html);
1871 $header_html = str_replace('{button}', '', $header_html);
1874 if ($this->_fieldsetsOpen
> 0) {
1875 $this->_html
.= $this->_closeFieldsetTemplate
;
1876 $this->_fieldsetsOpen
--;
1879 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
1880 if ($this->_showAdvanced
){
1881 $advclass = ' class="advanced"';
1883 $advclass = ' class="advanced hide"';
1885 if (isset($this->_advancedElements
[$name])){
1886 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1888 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1890 $this->_html
.= $openFieldsetTemplate . $header_html;
1891 $this->_fieldsetsOpen++
;
1892 } // end func renderHeader
1894 function getStopFieldsetElements(){
1895 return $this->_stopFieldsetElements
;
1900 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1902 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1903 MoodleQuickForm
::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1904 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1905 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1906 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1907 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1908 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1909 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1910 MoodleQuickForm
::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
1911 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1912 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1913 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1914 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1915 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1916 MoodleQuickForm
::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1917 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1918 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1919 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1920 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1921 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1922 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1923 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1924 MoodleQuickForm
::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1925 MoodleQuickForm
::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1926 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1927 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1928 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1929 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
1930 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
1931 MoodleQuickForm
::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');