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 //setup.php icludes our hacked pear libs first
24 require_once 'HTML/QuickForm.php';
25 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
26 require_once 'HTML/QuickForm/Renderer/Tableless.php';
28 require_once $CFG->libdir
.'/uploadlib.php';
31 * Callback called when PEAR throws an error
33 * @param PEAR_Error $error
35 function pear_handle_error($error){
36 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
37 echo '<br /> <strong>Backtrace </strong>:';
38 print_object($error->backtrace
);
41 if ($CFG->debug
>= DEBUG_ALL
){
42 PEAR
::setErrorHandling(PEAR_ERROR_CALLBACK
, 'pear_handle_error');
47 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
48 * use this class you should write a class definition which extends this class or a more specific
49 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
51 * You will write your own definition() method which performs the form set up.
54 var $_formname; // form name
56 * quickform object definition
58 * @var MoodleQuickForm
72 var $_upload_manager; //
74 * definition_after_data executed flag
75 * @var definition_finalized
77 var $_definition_finalized = false;
80 * The constructor function calls the abstract function definition() and it will then
81 * process and clean and attempt to validate incoming data.
83 * It will call your custom validate method to validate data and will also check any rules
84 * you have specified in definition using addRule
86 * The name of the form (id attribute of the form) is automatically generated depending on
87 * the name you gave the class extending moodleform. You should call your class something
90 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
91 * current url. If a moodle_url object then outputs params as hidden variables.
92 * @param array $customdata if your form defintion method needs access to data such as $course
93 * $cm, etc. to construct the form definition then pass it in this array. You can
94 * use globals for somethings.
95 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
96 * be merged and used as incoming data to the form.
97 * @param string $target target frame for form submission. You will rarely use this. Don't use
98 * it if you don't need to as the target attribute is deprecated in xhtml
100 * @param mixed $attributes you can pass a string of html attributes here or an array.
103 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
105 $action = strip_querystring(qualified_me());
108 $this->_formname
= get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
109 $this->_customdata
= $customdata;
110 $this->_form
=& new MoodleQuickForm($this->_formname
, $method, $action, $target, $attributes);
112 $this->_form
->hardFreeze();
114 $this->set_upload_manager(new upload_manager());
118 $this->_form
->addElement('hidden', 'sesskey', null); // automatic sesskey protection
119 $this->_form
->setDefault('sesskey', sesskey());
120 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
121 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
122 $this->_form
->_setDefaultRuleMessages();
124 // we have to know all input types before processing submission ;-)
125 $this->_process_submission($method);
129 * To autofocus on first form element or first element with error.
131 * @param string $name if this is set then the focus is forced to a field with this name
133 * @return string javascript to select form element with first error or
134 * first element if no errors. Use this as a parameter
135 * when calling print_header
137 function focus($name=NULL) {
138 $form =& $this->_form
;
139 $elkeys = array_keys($form->_elementIndex
);
141 if (isset($form->_errors
) && 0 != count($form->_errors
)){
142 $errorkeys = array_keys($form->_errors
);
143 $elkeys = array_intersect($elkeys, $errorkeys);
147 if ($error or empty($name)) {
149 while (empty($names) and !empty($elkeys)) {
150 $el = array_shift($elkeys);
151 $names = $form->_getElNamesRecursive($el);
153 if (!empty($names)) {
154 $name = array_shift($names);
160 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
167 * Internal method. Alters submitted data to be suitable for quickforms processing.
168 * Must be called when the form is fully set up.
170 function _process_submission($method) {
171 $submission = array();
172 if ($method == 'post') {
173 if (!empty($_POST)) {
174 $submission = $_POST;
177 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
180 // following trick is needed to enable proper sesskey checks when using GET forms
181 // the _qf__.$this->_formname serves as a marker that form was actually submitted
182 if (array_key_exists('_qf__'.$this->_formname
, $submission) and $submission['_qf__'.$this->_formname
] == 1) {
183 if (!confirm_sesskey()) {
184 print_error('invalidsesskey');
188 $submission = array();
192 $this->_form
->updateSubmission($submission, $files);
196 * Internal method. Validates all uploaded files.
198 function _validate_files(&$files) {
201 if (empty($_FILES)) {
202 // we do not need to do any checks because no files were submitted
203 // note: server side rules do not work for files - use custom verification in validate() instead
207 $mform =& $this->_form
;
210 $status = $this->_upload_manager
->preprocess_files();
212 // now check that we really want each file
213 foreach ($_FILES as $elname=>$file) {
214 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
215 $required = $mform->isElementRequired($elname);
216 if (!empty($this->_upload_manager
->files
[$elname]['uploadlog']) and empty($this->_upload_manager
->files
[$elname]['clear'])) {
217 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE
) {
218 // file not uploaded and not required - ignore it
221 $errors[$elname] = $this->_upload_manager
->files
[$elname]['uploadlog'];
223 } else if (!empty($this->_upload_manager
->files
[$elname]['clear'])) {
224 $files[$elname] = $this->_upload_manager
->files
[$elname]['tmp_name'];
227 error('Incorrect upload attempt!');
231 // return errors if found
232 if ($status and 0 == count($errors)){
242 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
243 * form definition (new entry form); this function is used to load in data where values
244 * already exist and data is being edited (edit entry form).
246 * @param mixed $default_values object or array of default values
247 * @param bool $slased true if magic quotes applied to data values
249 function set_data($default_values, $slashed=false) {
250 if (is_object($default_values)) {
251 $default_values = (array)$default_values;
253 $filter = $slashed ?
'stripslashes' : NULL;
254 $this->_form
->setDefaults($default_values, $filter);
258 * Set custom upload manager.
259 * Must be used BEFORE creating of file element!
261 * @param object $um - custom upload manager
263 function set_upload_manager($um=false) {
265 $um = new upload_manager();
267 $this->_upload_manager
= $um;
269 $this->_form
->setMaxFileSize($um->config
->maxbytes
);
273 * Check that form was submitted. Does not check validity of submitted data.
275 * @return bool true if form properly submitted
277 function is_submitted() {
278 return $this->_form
->isSubmitted();
281 function no_submit_button_pressed(){
282 static $nosubmit = null; // one check is enough
283 if (!is_null($nosubmit)){
286 $mform =& $this->_form
;
288 if (!$this->is_submitted()){
291 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
292 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
302 * Check that form data is valid.
304 * @return bool true if form data valid
306 function is_validated() {
307 static $validated = null; // one validation is enough
308 $mform =& $this->_form
;
310 //finalize the form definition before any processing
311 if (!$this->_definition_finalized
) {
312 $this->_definition_finalized
= true;
313 $this->definition_after_data();
316 if ($this->no_submit_button_pressed()){
318 } elseif ($validated === null) {
319 $internal_val = $mform->validate();
322 $file_val = $this->_validate_files($files);
323 if ($file_val !== true) {
324 if (!empty($file_val)) {
325 foreach ($file_val as $element=>$msg) {
326 $mform->setElementError($element, $msg);
332 $data = $mform->exportValues(null, true);
333 $moodle_val = $this->validation($data, $files);
334 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
335 // non-empty array means errors
336 foreach ($moodle_val as $element=>$msg) {
337 $mform->setElementError($element, $msg);
342 // anything else means validation ok
346 $validated = ($internal_val and $moodle_val and $file_val);
352 * Return true if a cancel button has been pressed resulting in the form being submitted.
354 * @return boolean true if a cancel button has been pressed
356 function is_cancelled(){
357 $mform =& $this->_form
;
358 if ($mform->isSubmitted()){
359 foreach ($mform->_cancelButtons
as $cancelbutton){
360 if (optional_param($cancelbutton, 0, PARAM_RAW
)){
369 * Return submitted data if properly submitted or returns NULL if validation fails or
370 * if there is no submitted data.
372 * @param bool $slashed true means return data with addslashes applied
373 * @return object submitted data; NULL if not valid or not submitted
375 function get_data($slashed=true) {
376 $mform =& $this->_form
;
378 if ($this->is_submitted() and $this->is_validated()) {
379 $data = $mform->exportValues(null, $slashed);
380 unset($data['sesskey']); // we do not need to return sesskey
381 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
385 return (object)$data;
393 * Return submitted data without validation or NULL if there is no submitted data.
395 * @param bool $slashed true means return data with addslashes applied
396 * @return object submitted data; NULL if not submitted
398 function get_submitted_data($slashed=true) {
399 $mform =& $this->_form
;
401 if ($this->is_submitted()) {
402 $data = $mform->exportValues(null, $slashed);
403 unset($data['sesskey']); // we do not need to return sesskey
404 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
408 return (object)$data;
416 * Save verified uploaded files into directory. Upload process can be customised from definition()
417 * method by creating instance of upload manager and storing it in $this->_upload_form
419 * @param string $destination where to store uploaded files
420 * @return bool success
422 function save_files($destination) {
423 if ($this->is_submitted() and $this->is_validated()) {
424 return $this->_upload_manager
->save_files($destination);
430 * If we're only handling one file (if inputname was given in the constructor)
431 * this will return the (possibly changed) filename of the file.
432 * @return mixed false in case of failure, string if ok
434 function get_new_filename() {
435 return $this->_upload_manager
->get_new_filename();
439 * Get content of uploaded file.
440 * @param $element name of file upload element
441 * @return mixed false in case of failure, string if ok
443 function get_file_content($elname) {
444 if (!$this->is_submitted() or !$this->is_validated()) {
448 if (!$this->_form
->elementExists($elname)) {
452 if (empty($this->_upload_manager
->files
[$elname]['clear'])) {
456 if (empty($this->_upload_manager
->files
[$elname]['tmp_name'])) {
461 $file = @fopen
($this->_upload_manager
->files
[$elname]['tmp_name'], "rb");
463 while (!feof($file)) {
464 $data .= fread($file, 1024); // TODO: do we really have to do this?
477 //finalize the form definition if not yet done
478 if (!$this->_definition_finalized
) {
479 $this->_definition_finalized
= true;
480 $this->definition_after_data();
482 $this->_form
->display();
486 * Abstract method - always override!
488 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
490 function definition() {
491 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
495 * Dummy stub method - override if you need to setup the form depending on current
496 * values. This method is called after definition(), data submission and set_data().
497 * All form setup that is dependent on form values should go in here.
499 function definition_after_data(){
503 * Dummy stub method - override if you needed to perform some extra validation.
504 * If there are errors return array of errors ("fieldname"=>"error message"),
505 * otherwise true if ok.
507 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
509 * @param array $data array of ("fieldname"=>value) of submitted data
510 * @param array $files array of uploaded files "element_name"=>tmp_file_path
511 * @return array of "element_name"=>"error_description" if there are errors,
512 * or an empty array if everything is OK (true allowed for backwards compatibility too).
514 function validation($data, $files) {
519 * Method to add a repeating group of elements to a form.
521 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
522 * @param integer $repeats no of times to repeat elements initially
523 * @param array $options Array of options to apply to elements. Array keys are element names.
524 * This is an array of arrays. The second sets of keys are the option types
526 * 'default' - default value is value
527 * 'type' - PARAM_* constant is value
528 * 'helpbutton' - helpbutton params array is value
529 * 'disabledif' - last three moodleform::disabledIf()
530 * params are value as an array
531 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
532 * @param string $addfieldsname name for button to add more fields
533 * @param int $addfieldsno how many fields to add at a time
534 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
535 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
536 * @return int no of repeats of element in this page
538 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
539 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
540 if ($addstring===null){
541 $addstring = get_string('addfields', 'form', $addfieldsno);
543 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
545 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT
);
546 $addfields = optional_param($addfieldsname, '', PARAM_TEXT
);
547 if (!empty($addfields)){
548 $repeats +
= $addfieldsno;
550 $mform =& $this->_form
;
551 $mform->registerNoSubmitButton($addfieldsname);
552 $mform->addElement('hidden', $repeathiddenname, $repeats);
553 //value not to be overridden by submitted value
554 $mform->setConstants(array($repeathiddenname=>$repeats));
555 for ($i=0; $i<$repeats; $i++
) {
556 foreach ($elementobjs as $elementobj){
557 $elementclone = fullclone($elementobj);
558 $name = $elementclone->getName();
560 $elementclone->setName($name."[$i]");
562 if (is_a($elementclone, 'HTML_QuickForm_header')){
563 $value=$elementclone->_text
;
564 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
567 $value=$elementclone->getLabel();
568 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
572 $mform->addElement($elementclone);
575 for ($i=0; $i<$repeats; $i++
) {
576 foreach ($options as $elementname => $elementoptions){
577 $pos=strpos($elementname, '[');
579 $realelementname = substr($elementname, 0, $pos+
1)."[$i]";
580 $realelementname .= substr($elementname, $pos+
1);
582 $realelementname = $elementname."[$i]";
584 foreach ($elementoptions as $option => $params){
588 $mform->setDefault($realelementname, $params);
591 $mform->setHelpButton($realelementname, $params);
594 $params = array_merge(array($realelementname), $params);
595 call_user_func_array(array(&$mform, 'disabledIf'), $params);
598 if (is_string($params)){
599 $params = array(null, $params, null, 'client');
601 $params = array_merge(array($realelementname), $params);
602 call_user_func_array(array(&$mform, 'addRule'), $params);
609 $mform->addElement('submit', $addfieldsname, $addstring);
611 if (!$addbuttoninside) {
612 $mform->closeHeaderBefore($addfieldsname);
619 * Adds a link/button that controls the checked state of a group of checkboxes.
620 * @param int $groupid The id of the group of advcheckboxes this element controls
621 * @param string $text The text of the link. Defaults to "select all/none"
622 * @param array $attributes associative array of HTML attributes
623 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
625 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
628 $text = get_string('selectallornone', 'form');
631 $mform = $this->_form
;
632 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT
);
634 if ($select_value == 0 ||
is_null($select_value)) {
635 $new_select_value = 1;
637 $new_select_value = 0;
640 $mform->addElement('hidden', "checkbox_controller$groupid");
641 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
643 // Locate all checkboxes for this group and set their value, IF the optional param was given
644 if (!is_null($select_value)) {
645 foreach ($this->_form
->_elements
as $element) {
646 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
647 $mform->setConstants(array($element->getAttribute('name') => $select_value));
652 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
653 $mform->registerNoSubmitButton($checkbox_controller_name);
655 // Prepare Javascript for submit element
656 $js = "\n//<![CDATA[\n";
657 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
659 function html_quickform_toggle_checkboxes(group) {
660 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
661 var newvalue = false;
662 var global = eval('html_quickform_checkboxgroup' + group + ';');
664 eval('html_quickform_checkboxgroup' + group + ' = 0;');
667 eval('html_quickform_checkboxgroup' + group + ' = 1;');
668 newvalue = 'checked';
671 for (i = 0; i < checkboxes.length; i++) {
672 checkboxes[i].checked = newvalue;
676 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
678 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
682 require_once("$CFG->libdir/form/submitlink.php");
683 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
684 $submitlink->_js
= $js;
685 $submitlink->_onclick
= "html_quickform_toggle_checkboxes($groupid); return false;";
686 $mform->addElement($submitlink);
687 $mform->setDefault($checkbox_controller_name, $text);
691 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
692 * if you don't want a cancel button in your form. If you have a cancel button make sure you
693 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
694 * get data with get_data().
696 * @param boolean $cancel whether to show cancel button, default true
697 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
699 function add_action_buttons($cancel = true, $submitlabel=null){
700 if (is_null($submitlabel)){
701 $submitlabel = get_string('savechanges');
703 $mform =& $this->_form
;
705 //when two elements we need a group
706 $buttonarray=array();
707 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
708 $buttonarray[] = &$mform->createElement('cancel');
709 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
710 $mform->closeHeaderBefore('buttonar');
713 $mform->addElement('submit', 'submitbutton', $submitlabel);
714 $mform->closeHeaderBefore('submitbutton');
720 * You never extend this class directly. The class methods of this class are available from
721 * the private $this->_form property on moodleform and its children. You generally only
722 * call methods on this class from within abstract methods that you override on moodleform such
723 * as definition and definition_after_data
726 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
727 var $_types = array();
728 var $_dependencies = array();
730 * Array of buttons that if pressed do not result in the processing of the form.
734 var $_noSubmitButtons=array();
736 * Array of buttons that if pressed do not result in the processing of the form.
740 var $_cancelButtons=array();
743 * Array whose keys are element names. If the key exists this is a advanced element
747 var $_advancedElements = array();
750 * Whether to display advanced elements (on page load)
754 var $_showAdvanced = null;
757 * The form name is derrived from the class name of the wrapper minus the trailing form
758 * It is a name with words joined by underscores whereas the id attribute is words joined by
766 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
770 var $_pageparams = '';
773 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
774 * @param string $formName Form's name.
775 * @param string $method (optional)Form's method defaults to 'POST'
776 * @param mixed $action (optional)Form's action - string or moodle_url
777 * @param string $target (optional)Form's target defaults to none
778 * @param mixed $attributes (optional)Extra attributes for <form> tag
779 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
782 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
785 static $formcounter = 1;
787 HTML_Common
::HTML_Common($attributes);
788 $target = empty($target) ?
array() : array('target' => $target);
789 $this->_formName
= $formName;
790 if (is_a($action, 'moodle_url')){
791 $this->_pageparams
= $action->hidden_params_out();
792 $action = $action->out(true);
794 $this->_pageparams
= '';
796 //no 'name' atttribute for form in xhtml strict :
797 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) +
$target;
799 $this->updateAttributes($attributes);
801 //this is custom stuff for Moodle :
802 $oldclass= $this->getAttribute('class');
803 if (!empty($oldclass)){
804 $this->updateAttributes(array('class'=>$oldclass.' mform'));
806 $this->updateAttributes(array('class'=>'mform'));
808 $this->_reqHTML
= '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />';
809 $this->_advancedHTML
= '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath
.'/adv.gif'.'" />';
810 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />'));
811 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
815 * Use this method to indicate an element in a form is an advanced field. If items in a form
816 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
817 * form so the user can decide whether to display advanced form controls.
819 * If you set a header element to advanced then all elements it contains will also be set as advanced.
821 * @param string $elementName group or element name (not the element name of something inside a group).
822 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
824 function setAdvanced($elementName, $advanced=true){
826 $this->_advancedElements
[$elementName]='';
827 } elseif (isset($this->_advancedElements
[$elementName])) {
828 unset($this->_advancedElements
[$elementName]);
830 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
831 $this->setShowAdvanced();
832 $this->registerNoSubmitButton('mform_showadvanced');
834 $this->addElement('hidden', 'mform_showadvanced_last');
838 * Set whether to show advanced elements in the form on first displaying form. Default is not to
839 * display advanced elements in the form until 'Show Advanced' is pressed.
841 * You can get the last state of the form and possibly save it for this user by using
842 * value 'mform_showadvanced_last' in submitted data.
844 * @param boolean $showadvancedNow
846 function setShowAdvanced($showadvancedNow = null){
847 if ($showadvancedNow === null){
848 if ($this->_showAdvanced
!== null){
850 } else { //if setShowAdvanced is called without any preference
851 //make the default to not show advanced elements.
852 $showadvancedNow = get_user_preferences(
853 moodle_strtolower($this->_formName
.'_showadvanced', 0));
856 //value of hidden element
857 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT
);
859 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW
);
860 //toggle if button pressed or else stay the same
861 if ($hiddenLast == -1) {
862 $next = $showadvancedNow;
863 } elseif ($buttonPressed) { //toggle on button press
864 $next = !$hiddenLast;
868 $this->_showAdvanced
= $next;
869 if ($showadvancedNow != $next){
870 set_user_preference($this->_formName
.'_showadvanced', $next);
872 $this->setConstants(array('mform_showadvanced_last'=>$next));
874 function getShowAdvanced(){
875 return $this->_showAdvanced
;
882 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
887 function accept(&$renderer) {
888 if (method_exists($renderer, 'setAdvancedElements')){
889 //check for visible fieldsets where all elements are advanced
890 //and mark these headers as advanced as well.
891 //And mark all elements in a advanced header as advanced
892 $stopFields = $renderer->getStopFieldSetElements();
894 $lastHeaderAdvanced = false;
895 $anyAdvanced = false;
896 foreach (array_keys($this->_elements
) as $elementIndex){
897 $element =& $this->_elements
[$elementIndex];
899 // if closing header and any contained element was advanced then mark it as advanced
900 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
901 if ($anyAdvanced && !is_null($lastHeader)){
902 $this->setAdvanced($lastHeader->getName());
904 $lastHeaderAdvanced = false;
907 } elseif ($lastHeaderAdvanced) {
908 $this->setAdvanced($element->getName());
911 if ($element->getType()=='header'){
912 $lastHeader =& $element;
913 $anyAdvanced = false;
914 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
915 } elseif (isset($this->_advancedElements
[$element->getName()])){
919 // the last header may not be closed yet...
920 if ($anyAdvanced && !is_null($lastHeader)){
921 $this->setAdvanced($lastHeader->getName());
923 $renderer->setAdvancedElements($this->_advancedElements
);
926 parent
::accept($renderer);
931 function closeHeaderBefore($elementName){
932 $renderer =& $this->defaultRenderer();
933 $renderer->addStopFieldsetElements($elementName);
937 * Should be used for all elements of a form except for select, radio and checkboxes which
938 * clean their own data.
940 * @param string $elementname
941 * @param integer $paramtype use the constants PARAM_*.
942 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
943 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
944 * It will strip all html tags. But will still let tags for multilang support
946 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
947 * html editor. Data from the editor is later cleaned before display using
948 * format_text() function. PARAM_RAW can also be used for data that is validated
949 * by some other way or printed by p() or s().
950 * * PARAM_INT should be used for integers.
951 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
954 function setType($elementname, $paramtype) {
955 $this->_types
[$elementname] = $paramtype;
959 * See description of setType above. This can be used to set several types at once.
961 * @param array $paramtypes
963 function setTypes($paramtypes) {
964 $this->_types
= $paramtypes +
$this->_types
;
967 function updateSubmission($submission, $files) {
968 $this->_flagSubmitted
= false;
970 if (empty($submission)) {
971 $this->_submitValues
= array();
973 foreach ($submission as $key=>$s) {
974 if (array_key_exists($key, $this->_types
)) {
975 $submission[$key] = clean_param($s, $this->_types
[$key]);
978 $this->_submitValues
= $this->_recursiveFilter('stripslashes', $submission);
979 $this->_flagSubmitted
= true;
983 $this->_submitFiles
= array();
985 if (1 == get_magic_quotes_gpc()) {
986 foreach (array_keys($files) as $elname) {
987 // dangerous characters in filenames are cleaned later in upload_manager
988 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
991 $this->_submitFiles
= $files;
992 $this->_flagSubmitted
= true;
995 // need to tell all elements that they need to update their value attribute.
996 foreach (array_keys($this->_elements
) as $key) {
997 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
1001 function getReqHTML(){
1002 return $this->_reqHTML
;
1005 function getAdvancedHTML(){
1006 return $this->_advancedHTML
;
1010 * Initializes a default form value. Used to specify the default for a new entry where
1011 * no data is loaded in using moodleform::set_data()
1013 * @param string $elementname element name
1014 * @param mixed $values values for that element name
1015 * @param bool $slashed the default value is slashed
1019 function setDefault($elementName, $defaultValue, $slashed=false){
1020 $filter = $slashed ?
'stripslashes' : NULL;
1021 $this->setDefaults(array($elementName=>$defaultValue), $filter);
1022 } // end func setDefault
1024 * Add an array of buttons to the form
1025 * @param array $buttons An associative array representing help button to attach to
1026 * to the form. keys of array correspond to names of elements in form.
1030 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1032 foreach ($buttons as $elementname => $button){
1033 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1037 * Add a single button.
1039 * @param string $elementname name of the element to add the item to
1040 * @param array $button - arguments to pass to function $function
1041 * @param boolean $suppresscheck - whether to throw an error if the element
1043 * @param string $function - function to generate html from the arguments in $button
1045 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
1046 if (array_key_exists($elementname, $this->_elementIndex
)){
1047 //_elements has a numeric index, this code accesses the elements by name
1048 $element=&$this->_elements
[$this->_elementIndex
[$elementname]];
1049 if (method_exists($element, 'setHelpButton')){
1050 $element->setHelpButton($button, $function);
1053 $a->name
=$element->getName();
1054 $a->classname
=get_class($element);
1055 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
1057 }elseif (!$suppresscheck){
1058 print_error('nonexistentformelements', 'form', '', $elementname);
1063 * Set constant value not overriden by _POST or _GET
1064 * note: this does not work for complex names with [] :-(
1065 * @param string $elname name of element
1066 * @param mixed $value
1069 function setConstant($elname, $value) {
1070 $this->_constantValues
= HTML_QuickForm
::arrayMerge($this->_constantValues
, array($elname=>$value));
1071 $element =& $this->getElement($elname);
1072 $element->onQuickFormEvent('updateValue', null, $this);
1075 function exportValues($elementList= null, $addslashes=true){
1076 $unfiltered = array();
1077 if (null === $elementList) {
1078 // iterate over all elements, calling their exportValue() methods
1079 $emptyarray = array();
1080 foreach (array_keys($this->_elements
) as $key) {
1081 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
){
1082 $value = $this->_elements
[$key]->exportValue($emptyarray, true);
1084 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
1087 if (is_array($value)) {
1088 // This shit throws a bogus warning in PHP 4.3.x
1089 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
1093 if (!is_array($elementList)) {
1094 $elementList = array_map('trim', explode(',', $elementList));
1096 foreach ($elementList as $elementName) {
1097 $value = $this->exportValue($elementName);
1098 if (PEAR
::isError($value)) {
1101 $unfiltered[$elementName] = $value;
1106 return $this->_recursiveFilter('addslashes', $unfiltered);
1112 * Adds a validation rule for the given field
1114 * If the element is in fact a group, it will be considered as a whole.
1115 * To validate grouped elements as separated entities,
1116 * use addGroupRule instead of addRule.
1118 * @param string $element Form element name
1119 * @param string $message Message to display for invalid data
1120 * @param string $type Rule type, use getRegisteredRules() to get types
1121 * @param string $format (optional)Required for extra rule data
1122 * @param string $validation (optional)Where to perform validation: "server", "client"
1123 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1124 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1127 * @throws HTML_QuickForm_Error
1129 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1131 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
1132 if ($validation == 'client') {
1133 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1136 } // end func addRule
1138 * Adds a validation rule for the given group of elements
1140 * Only groups with a name can be assigned a validation rule
1141 * Use addGroupRule when you need to validate elements inside the group.
1142 * Use addRule if you need to validate the group as a whole. In this case,
1143 * the same rule will be applied to all elements in the group.
1144 * Use addRule if you need to validate the group against a function.
1146 * @param string $group Form group name
1147 * @param mixed $arg1 Array for multiple elements or error message string for one element
1148 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1149 * @param string $format (optional)Required for extra rule data
1150 * @param int $howmany (optional)How many valid elements should be in the group
1151 * @param string $validation (optional)Where to perform validation: "server", "client"
1152 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1155 * @throws HTML_QuickForm_Error
1157 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1159 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1160 if (is_array($arg1)) {
1161 foreach ($arg1 as $rules) {
1162 foreach ($rules as $rule) {
1163 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
1165 if ('client' == $validation) {
1166 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1170 } elseif (is_string($arg1)) {
1172 if ($validation == 'client') {
1173 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1176 } // end func addGroupRule
1180 * Returns the client side validation script
1182 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1183 * and slightly modified to run rules per-element
1184 * Needed to override this because of an error with client side validation of grouped elements.
1187 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1189 function getValidationScript()
1191 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1195 include_once('HTML/QuickForm/RuleRegistry.php');
1196 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1207 foreach ($this->_rules
as $elementName => $rules) {
1208 foreach ($rules as $rule) {
1209 if ('client' == $rule['validation']) {
1210 unset($element); //TODO: find out how to properly initialize it
1212 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1213 $rule['message'] = strtr($rule['message'], $js_escape);
1215 if (isset($rule['group'])) {
1216 $group =& $this->getElement($rule['group']);
1217 // No JavaScript validation for frozen elements
1218 if ($group->isFrozen()) {
1221 $elements =& $group->getElements();
1222 foreach (array_keys($elements) as $key) {
1223 if ($elementName == $group->getElementName($key)) {
1224 $element =& $elements[$key];
1228 } elseif ($dependent) {
1230 $element[] =& $this->getElement($elementName);
1231 foreach ($rule['dependent'] as $elName) {
1232 $element[] =& $this->getElement($elName);
1235 $element =& $this->getElement($elementName);
1237 // No JavaScript validation for frozen elements
1238 if (is_object($element) && $element->isFrozen()) {
1240 } elseif (is_array($element)) {
1241 foreach (array_keys($element) as $key) {
1242 if ($element[$key]->isFrozen()) {
1247 // Fix for bug displaying errors for elements in a group
1248 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1249 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1250 $test[$elementName][1]=$element;
1256 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1257 // the form, and then that form field gets corrupted by the code that follows.
1261 <script type="text/javascript">
1264 var skipClientValidation = false;
1266 function qf_errorHandler(element, _qfMsg) {
1267 div = element.parentNode;
1268 if (_qfMsg != \'\') {
1269 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1271 errorSpan = document.createElement("span");
1272 errorSpan.id = \'id_error_\'+element.name;
1273 errorSpan.className = "error";
1274 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1277 while (errorSpan.firstChild) {
1278 errorSpan.removeChild(errorSpan.firstChild);
1281 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1282 errorSpan.appendChild(document.createElement("br"));
1284 if (div.className.substr(div.className.length - 6, 6) != " error"
1285 && div.className != "error") {
1286 div.className += " error";
1291 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1293 errorSpan.parentNode.removeChild(errorSpan);
1296 if (div.className.substr(div.className.length - 6, 6) == " error") {
1297 div.className = div.className.substr(0, div.className.length - 6);
1298 } else if (div.className == "error") {
1306 foreach ($test as $elementName => $jsandelement) {
1307 // Fix for bug displaying errors for elements in a group
1309 list($jsArr,$element)=$jsandelement;
1312 function validate_' . $this->_formName
. '_' . $elementName . '(element) {
1314 var errFlag = new Array();
1317 var frm = element.parentNode;
1318 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1319 frm = frm.parentNode;
1321 ' . join("\n", $jsArr) . '
1322 return qf_errorHandler(element, _qfMsg);
1326 ret = validate_' . $this->_formName
. '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1327 if (!ret && !first_focus) {
1329 frm.elements[\''.$elementName.'\'].focus();
1333 // Fix for bug displaying errors for elements in a group
1335 //$element =& $this->getElement($elementName);
1337 $valFunc = 'validate_' . $this->_formName
. '_' . $elementName . '(this)';
1338 $onBlur = $element->getAttribute('onBlur');
1339 $onChange = $element->getAttribute('onChange');
1340 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1341 'onChange' => $onChange . $valFunc));
1343 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1345 function validate_' . $this->_formName
. '(frm) {
1346 if (skipClientValidation) {
1351 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1352 var first_focus = false;
1353 ' . $validateJS . ';
1359 } // end func getValidationScript
1360 function _setDefaultRuleMessages(){
1361 foreach ($this->_rules
as $field => $rulesarr){
1362 foreach ($rulesarr as $key => $rule){
1363 if ($rule['message']===null){
1365 $a->format
=$rule['format'];
1366 $str=get_string('err_'.$rule['type'], 'form', $a);
1367 if (strpos($str, '[[')!==0){
1368 $this->_rules
[$field][$key]['message']=$str;
1375 function getLockOptionEndScript(){
1377 $iname = $this->getAttribute('id').'items';
1378 $js = '<script type="text/javascript">'."\n";
1379 $js .= '//<![CDATA['."\n";
1380 $js .= "var $iname = Array();\n";
1382 foreach ($this->_dependencies
as $dependentOn => $conditions){
1383 $js .= "{$iname}['$dependentOn'] = Array();\n";
1384 foreach ($conditions as $condition=>$values) {
1385 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1386 foreach ($values as $value=>$dependents) {
1387 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1389 foreach ($dependents as $dependent) {
1390 $elements = $this->_getElNamesRecursive($dependent);
1391 if (empty($elements)) {
1392 // probably element inside of some group
1393 $elements = array($dependent);
1395 foreach($elements as $element) {
1396 if ($element == $dependentOn) {
1399 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1406 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1408 $js .='</script>'."\n";
1412 function _getElNamesRecursive($element) {
1413 if (is_string($element)) {
1414 if (!$this->elementExists($element)) {
1417 $element = $this->getElement($element);
1420 if (is_a($element, 'HTML_QuickForm_group')) {
1421 $elsInGroup = $element->getElements();
1423 foreach ($elsInGroup as $elInGroup){
1424 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1425 // not sure if this would work - groups nested in groups
1426 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1428 $elNames[] = $element->getElementName($elInGroup->getName());
1432 } else if (is_a($element, 'HTML_QuickForm_header')) {
1435 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1438 } else if (method_exists($element, 'getPrivateName')) {
1439 return array($element->getPrivateName());
1442 $elNames = array($element->getName());
1449 * Adds a dependency for $elementName which will be disabled if $condition is met.
1450 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1451 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1452 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1453 * of the $dependentOn element is $condition (such as equal) to $value.
1455 * @param string $elementName the name of the element which will be disabled
1456 * @param string $dependentOn the name of the element whose state will be checked for
1458 * @param string $condition the condition to check
1459 * @param mixed $value used in conjunction with condition.
1461 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1462 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
1463 $this->_dependencies
[$dependentOn] = array();
1465 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
1466 $this->_dependencies
[$dependentOn][$condition] = array();
1468 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
1469 $this->_dependencies
[$dependentOn][$condition][$value] = array();
1471 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
1474 function registerNoSubmitButton($buttonname){
1475 $this->_noSubmitButtons
[]=$buttonname;
1478 function isNoSubmitButton($buttonname){
1479 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
1482 function _registerCancelButton($addfieldsname){
1483 $this->_cancelButtons
[]=$addfieldsname;
1486 * Displays elements without HTML input tags.
1487 * This method is different to freeze() in that it makes sure no hidden
1488 * elements are included in the form.
1489 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1491 * This function also removes all previously defined rules.
1493 * @param mixed $elementList array or string of element(s) to be frozen
1496 * @throws HTML_QuickForm_Error
1498 function hardFreeze($elementList=null)
1500 if (!isset($elementList)) {
1501 $this->_freezeAll
= true;
1502 $elementList = array();
1504 if (!is_array($elementList)) {
1505 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1507 $elementList = array_flip($elementList);
1510 foreach (array_keys($this->_elements
) as $key) {
1511 $name = $this->_elements
[$key]->getName();
1512 if ($this->_freezeAll ||
isset($elementList[$name])) {
1513 $this->_elements
[$key]->freeze();
1514 $this->_elements
[$key]->setPersistantFreeze(false);
1515 unset($elementList[$name]);
1518 $this->_rules
[$name] = array();
1519 // if field is required, remove the rule
1520 $unset = array_search($name, $this->_required
);
1521 if ($unset !== false) {
1522 unset($this->_required
[$unset]);
1527 if (!empty($elementList)) {
1528 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);
1533 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1535 * This function also removes all previously defined rules of elements it freezes.
1537 * @param array $elementList array or string of element(s) not to be frozen
1540 * @throws HTML_QuickForm_Error
1542 function hardFreezeAllVisibleExcept($elementList)
1544 $elementList = array_flip($elementList);
1545 foreach (array_keys($this->_elements
) as $key) {
1546 $name = $this->_elements
[$key]->getName();
1547 $type = $this->_elements
[$key]->getType();
1549 if ($type == 'hidden'){
1550 // leave hidden types as they are
1551 } elseif (!isset($elementList[$name])) {
1552 $this->_elements
[$key]->freeze();
1553 $this->_elements
[$key]->setPersistantFreeze(false);
1556 $this->_rules
[$name] = array();
1557 // if field is required, remove the rule
1558 $unset = array_search($name, $this->_required
);
1559 if ($unset !== false) {
1560 unset($this->_required
[$unset]);
1567 * Tells whether the form was already submitted
1569 * This is useful since the _submitFiles and _submitValues arrays
1570 * may be completely empty after the trackSubmit value is removed.
1575 function isSubmitted()
1577 return parent
::isSubmitted() && (!$this->isFrozen());
1583 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1584 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1586 * Stylesheet is part of standard theme and should be automatically included.
1588 * @author Jamie Pratt <me@jamiep.org>
1589 * @license gpl license
1591 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
1594 * Element template array
1598 var $_elementTemplates;
1600 * Template used when opening a hidden fieldset
1601 * (i.e. a fieldset that is opened when there is no header element)
1605 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1607 * Header Template string
1611 var $_headerTemplate =
1612 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1615 * Template used when opening a fieldset
1619 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1622 * Template used when closing a fieldset
1626 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1629 * Required Note template string
1633 var $_requiredNoteTemplate =
1634 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1636 var $_advancedElements = array();
1639 * Whether to display advanced elements (on page load)
1641 * @var integer 1 means show 0 means hide
1645 function MoodleQuickForm_Renderer(){
1646 // switch next two lines for ol li containers for form items.
1647 // $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>');
1648 $this->_elementTemplates
= array(
1649 '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>',
1651 '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>',
1653 '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>',
1657 parent
::HTML_QuickForm_Renderer_Tableless();
1660 function setAdvancedElements($elements){
1661 $this->_advancedElements
= $elements;
1665 * What to do when starting the form
1667 * @param MoodleQuickForm $form
1669 function startForm(&$form){
1670 $this->_reqHTML
= $form->getReqHTML();
1671 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
1672 $this->_advancedHTML
= $form->getAdvancedHTML();
1673 $this->_showAdvanced
= $form->getShowAdvanced();
1674 parent
::startForm($form);
1675 if ($form->isFrozen()){
1676 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
1678 $this->_hiddenHtml
.= $form->_pageparams
;
1684 function startGroup(&$group, $required, $error){
1685 if (method_exists($group, 'getElementTemplateType')){
1686 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
1688 $html = $this->_elementTemplates
['default'];
1691 if ($this->_showAdvanced
){
1692 $advclass = ' advanced';
1694 $advclass = ' advanced hide';
1696 if (isset($this->_advancedElements
[$group->getName()])){
1697 $html =str_replace(' {advanced}', $advclass, $html);
1698 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1700 $html =str_replace(' {advanced}', '', $html);
1701 $html =str_replace('{advancedimg}', '', $html);
1703 if (method_exists($group, 'getHelpButton')){
1704 $html =str_replace('{help}', $group->getHelpButton(), $html);
1706 $html =str_replace('{help}', '', $html);
1708 $html =str_replace('{name}', $group->getName(), $html);
1709 $html =str_replace('{type}', 'fgroup', $html);
1711 $this->_templates
[$group->getName()]=$html;
1712 // Fix for bug in tableless quickforms that didn't allow you to stop a
1713 // fieldset before a group of elements.
1714 // if the element name indicates the end of a fieldset, close the fieldset
1715 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
1716 && $this->_fieldsetsOpen
> 0
1718 $this->_html
.= $this->_closeFieldsetTemplate
;
1719 $this->_fieldsetsOpen
--;
1721 parent
::startGroup($group, $required, $error);
1724 function renderElement(&$element, $required, $error){
1725 //manipulate id of all elements before rendering
1726 if (!is_null($element->getAttribute('id'))) {
1727 $id = $element->getAttribute('id');
1729 $id = $element->getName();
1731 //strip qf_ prefix and replace '[' with '_' and strip ']'
1732 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1733 if (strpos($id, 'id_') !== 0){
1734 $element->updateAttributes(array('id'=>'id_'.$id));
1737 //adding stuff to place holders in template
1738 if (method_exists($element, 'getElementTemplateType')){
1739 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
1741 $html = $this->_elementTemplates
['default'];
1743 if ($this->_showAdvanced
){
1744 $advclass = ' advanced';
1746 $advclass = ' advanced hide';
1748 if (isset($this->_advancedElements
[$element->getName()])){
1749 $html =str_replace(' {advanced}', $advclass, $html);
1751 $html =str_replace(' {advanced}', '', $html);
1753 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
1754 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1756 $html =str_replace('{advancedimg}', '', $html);
1758 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1759 $html =str_replace('{name}', $element->getName(), $html);
1760 if (method_exists($element, 'getHelpButton')){
1761 $html = str_replace('{help}', $element->getHelpButton(), $html);
1763 $html = str_replace('{help}', '', $html);
1766 if (!isset($this->_templates
[$element->getName()])) {
1767 $this->_templates
[$element->getName()] = $html;
1770 parent
::renderElement($element, $required, $error);
1773 function finishForm(&$form){
1774 if ($form->isFrozen()){
1775 $this->_hiddenHtml
= '';
1777 parent
::finishForm($form);
1778 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1779 // add a lockoptions script
1780 $this->_html
= $this->_html
. "\n" . $script;
1784 * Called when visiting a header element
1786 * @param object An HTML_QuickForm_header element being visited
1790 function renderHeader(&$header) {
1791 $name = $header->getName();
1793 $id = empty($name) ?
'' : ' id="' . $name . '"';
1794 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1795 if (is_null($header->_text
)) {
1797 } elseif (!empty($name) && isset($this->_templates
[$name])) {
1798 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
1800 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
1803 if (isset($this->_advancedElements
[$name])){
1804 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
1806 $header_html =str_replace('{advancedimg}', '', $header_html);
1808 $elementName='mform_showadvanced';
1809 if ($this->_showAdvanced
==0){
1810 $buttonlabel = get_string('showadvanced', 'form');
1812 $buttonlabel = get_string('hideadvanced', 'form');
1815 if (isset($this->_advancedElements
[$name])){
1816 require_js(array('yui_yahoo', 'yui_event'));
1817 // this is tricky - the first submit button on form is "clicked" if user presses enter
1818 // we do not want to "submit" using advanced button if javascript active
1819 $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />';
1821 $buttonlabel = addslashes_js($buttonlabel);
1822 $showtext = addslashes_js(get_string('showadvanced', 'form'));
1823 $hidetext = addslashes_js(get_string('hideadvanced', 'form'));
1824 $button = '<script id="' . $name . '_script" type="text/javascript">' . "
1825 showAdvancedInit('{$name}_script', '$elementName', '$buttonlabel', '$hidetext', '$showtext');
1826 " . '</script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation
1828 $header_html = str_replace('{button}', $button, $header_html);
1830 $header_html = str_replace('{button}', '', $header_html);
1833 if ($this->_fieldsetsOpen
> 0) {
1834 $this->_html
.= $this->_closeFieldsetTemplate
;
1835 $this->_fieldsetsOpen
--;
1838 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
1839 if ($this->_showAdvanced
){
1840 $advclass = ' class="advanced"';
1842 $advclass = ' class="advanced hide"';
1844 if (isset($this->_advancedElements
[$name])){
1845 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1847 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1849 $this->_html
.= $openFieldsetTemplate . $header_html;
1850 $this->_fieldsetsOpen++
;
1851 } // end func renderHeader
1853 function getStopFieldsetElements(){
1854 return $this->_stopFieldsetElements
;
1859 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1861 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1862 MoodleQuickForm
::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1863 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1864 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1865 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1866 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1867 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1868 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1869 MoodleQuickForm
::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
1870 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1871 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1872 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1873 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1874 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1875 MoodleQuickForm
::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1876 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1877 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1878 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1879 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1880 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1881 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1882 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1883 MoodleQuickForm
::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1884 MoodleQuickForm
::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1885 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1886 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1887 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1888 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
1889 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
1890 MoodleQuickForm
::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');