3 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
5 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
6 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
7 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
10 * See examples of use of this library in course/edit.php and course/edit_form.php
13 * form defintion is used for both printing of form and processing and should be the same
14 * for both or you may lose some submitted data which won't be let through.
15 * you should be using setType for every form element except select, radio or checkbox
16 * elements, these elements clean themselves.
21 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
24 //setup.php icludes our hacked pear libs first
25 require_once 'HTML/QuickForm.php';
26 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
27 require_once 'HTML/QuickForm/Renderer/Tableless.php';
29 require_once $CFG->libdir
.'/uploadlib.php';
32 * Callback called when PEAR throws an error
34 * @param PEAR_Error $error
36 function pear_handle_error($error){
37 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
38 echo '<br /> <strong>Backtrace </strong>:';
39 print_object($error->backtrace
);
42 if ($CFG->debug
>= DEBUG_ALL
){
43 PEAR
::setErrorHandling(PEAR_ERROR_CALLBACK
, 'pear_handle_error');
48 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
49 * use this class you should write a class definition which extends this class or a more specific
50 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
52 * You will write your own definition() method which performs the form set up.
55 var $_formname; // form name
57 * quickform object definition
59 * @var MoodleQuickForm
73 var $_upload_manager; //
75 * definition_after_data executed flag
76 * @var definition_finalized
78 var $_definition_finalized = false;
81 * The constructor function calls the abstract function definition() and it will then
82 * process and clean and attempt to validate incoming data.
84 * It will call your custom validate method to validate data and will also check any rules
85 * you have specified in definition using addRule
87 * The name of the form (id attribute of the form) is automatically generated depending on
88 * the name you gave the class extending moodleform. You should call your class something
91 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
92 * current url. If a moodle_url object then outputs params as hidden variables.
93 * @param array $customdata if your form defintion method needs access to data such as $course
94 * $cm, etc. to construct the form definition then pass it in this array. You can
95 * use globals for somethings.
96 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
97 * be merged and used as incoming data to the form.
98 * @param string $target target frame for form submission. You will rarely use this. Don't use
99 * it if you don't need to as the target attribute is deprecated in xhtml
101 * @param mixed $attributes you can pass a string of html attributes here or an array.
104 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
106 $action = strip_querystring(qualified_me());
109 $this->_formname
= get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
110 $this->_customdata
= $customdata;
111 $this->_form
=& new MoodleQuickForm($this->_formname
, $method, $action, $target, $attributes);
113 $this->_form
->hardFreeze();
115 $this->set_upload_manager(new upload_manager());
119 $this->_form
->addElement('hidden', 'sesskey', null); // automatic sesskey protection
120 $this->_form
->setDefault('sesskey', sesskey());
121 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
122 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
123 $this->_form
->_setDefaultRuleMessages();
125 // we have to know all input types before processing submission ;-)
126 $this->_process_submission($method);
130 * To autofocus on first form element or first element with error.
132 * @param string $name if this is set then the focus is forced to a field with this name
134 * @return string javascript to select form element with first error or
135 * first element if no errors. Use this as a parameter
136 * when calling print_header
138 function focus($name=NULL) {
139 $form =& $this->_form
;
140 $elkeys = array_keys($form->_elementIndex
);
142 if (isset($form->_errors
) && 0 != count($form->_errors
)){
143 $errorkeys = array_keys($form->_errors
);
144 $elkeys = array_intersect($elkeys, $errorkeys);
148 if ($error or empty($name)) {
150 while (empty($names) and !empty($elkeys)) {
151 $el = array_shift($elkeys);
152 $names = $form->_getElNamesRecursive($el);
154 if (!empty($names)) {
155 $name = array_shift($names);
161 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
168 * Internal method. Alters submitted data to be suitable for quickforms processing.
169 * Must be called when the form is fully set up.
171 function _process_submission($method) {
172 $submission = array();
173 if ($method == 'post') {
174 if (!empty($_POST)) {
175 $submission = $_POST;
178 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
181 // following trick is needed to enable proper sesskey checks when using GET forms
182 // the _qf__.$this->_formname serves as a marker that form was actually submitted
183 if (array_key_exists('_qf__'.$this->_formname
, $submission) and $submission['_qf__'.$this->_formname
] == 1) {
184 if (!confirm_sesskey()) {
185 error('Incorrect sesskey submitted, form not accepted!');
189 $submission = array();
193 $this->_form
->updateSubmission($submission, $files);
197 * Internal method. Validates all uploaded files.
199 function _validate_files(&$files) {
202 if (empty($_FILES)) {
203 // we do not need to do any checks because no files were submitted
204 // note: server side rules do not work for files - use custom verification in validate() instead
208 $mform =& $this->_form
;
211 $status = $this->_upload_manager
->preprocess_files();
213 // now check that we really want each file
214 foreach ($_FILES as $elname=>$file) {
215 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
216 $required = $mform->isElementRequired($elname);
217 if (!empty($this->_upload_manager
->files
[$elname]['uploadlog']) and empty($this->_upload_manager
->files
[$elname]['clear'])) {
218 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE
) {
219 // file not uploaded and not required - ignore it
222 $errors[$elname] = $this->_upload_manager
->files
[$elname]['uploadlog'];
224 } else if (!empty($this->_upload_manager
->files
[$elname]['clear'])) {
225 $files[$elname] = $this->_upload_manager
->files
[$elname]['tmp_name'];
228 error('Incorrect upload attempt!');
232 // return errors if found
233 if ($status and 0 == count($errors)){
243 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
244 * form definition (new entry form); this function is used to load in data where values
245 * already exist and data is being edited (edit entry form).
247 * @param mixed $default_values object or array of default values
248 * @param bool $slased true if magic quotes applied to data values
250 function set_data($default_values, $slashed=false) {
251 if (is_object($default_values)) {
252 $default_values = (array)$default_values;
254 $filter = $slashed ?
'stripslashes' : NULL;
255 $this->_form
->setDefaults($default_values, $filter);
259 * Set custom upload manager.
260 * Must be used BEFORE creating of file element!
262 * @param object $um - custom upload manager
264 function set_upload_manager($um=false) {
266 $um = new upload_manager();
268 $this->_upload_manager
= $um;
270 $this->_form
->setMaxFileSize($um->config
->maxbytes
);
274 * Check that form was submitted. Does not check validity of submitted data.
276 * @return bool true if form properly submitted
278 function is_submitted() {
279 return $this->_form
->isSubmitted();
282 function no_submit_button_pressed(){
283 static $nosubmit = null; // one check is enough
284 if (!is_null($nosubmit)){
287 $mform =& $this->_form
;
289 if (!$this->is_submitted()){
292 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
293 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
303 * Check that form data is valid.
305 * @return bool true if form data valid
307 function is_validated() {
308 static $validated = null; // one validation is enough
309 $mform =& $this->_form
;
311 //finalize the form definition before any processing
312 if (!$this->_definition_finalized
) {
313 $this->_definition_finalized
= true;
314 $this->definition_after_data();
317 if ($this->no_submit_button_pressed()){
319 } elseif ($validated === null) {
320 $internal_val = $mform->validate();
323 $file_val = $this->_validate_files($files);
324 if ($file_val !== true) {
325 if (!empty($file_val)) {
326 foreach ($file_val as $element=>$msg) {
327 $mform->setElementError($element, $msg);
333 $data = $mform->exportValues(null, true);
334 $moodle_val = $this->validation($data, $files);
335 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
336 // non-empty array means errors
337 foreach ($moodle_val as $element=>$msg) {
338 $mform->setElementError($element, $msg);
343 // anything else means validation ok
347 $validated = ($internal_val and $moodle_val and $file_val);
353 * Return true if a cancel button has been pressed resulting in the form being submitted.
355 * @return boolean true if a cancel button has been pressed
357 function is_cancelled(){
358 $mform =& $this->_form
;
359 if ($mform->isSubmitted()){
360 foreach ($mform->_cancelButtons
as $cancelbutton){
361 if (optional_param($cancelbutton, 0, PARAM_RAW
)){
370 * Return submitted data if properly submitted or returns NULL if validation fails or
371 * if there is no submitted data.
373 * @param bool $slashed true means return data with addslashes applied
374 * @return object submitted data; NULL if not valid or not submitted
376 function get_data($slashed=true) {
377 $mform =& $this->_form
;
379 if ($this->is_submitted() and $this->is_validated()) {
380 $data = $mform->exportValues(null, $slashed);
381 unset($data['sesskey']); // we do not need to return sesskey
382 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
386 return (object)$data;
394 * Return submitted data without validation or NULL if there is no submitted data.
396 * @param bool $slashed true means return data with addslashes applied
397 * @return object submitted data; NULL if not submitted
399 function get_submitted_data($slashed=true) {
400 $mform =& $this->_form
;
402 if ($this->is_submitted()) {
403 $data = $mform->exportValues(null, $slashed);
404 unset($data['sesskey']); // we do not need to return sesskey
405 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
409 return (object)$data;
417 * Save verified uploaded files into directory. Upload process can be customised from definition()
418 * method by creating instance of upload manager and storing it in $this->_upload_form
420 * @param string $destination where to store uploaded files
421 * @return bool success
423 function save_files($destination) {
424 if ($this->is_submitted() and $this->is_validated()) {
425 return $this->_upload_manager
->save_files($destination);
431 * If we're only handling one file (if inputname was given in the constructor)
432 * this will return the (possibly changed) filename of the file.
433 * @return mixed false in case of failure, string if ok
435 function get_new_filename() {
436 return $this->_upload_manager
->get_new_filename();
440 * Get content of uploaded file.
441 * @param $element name of file upload element
442 * @return mixed false in case of failure, string if ok
444 function get_file_content($elname) {
445 if (!$this->is_submitted() or !$this->is_validated()) {
449 if (!$this->_form
->elementExists($elname)) {
453 if (empty($this->_upload_manager
->files
[$elname]['clear'])) {
457 if (empty($this->_upload_manager
->files
[$elname]['tmp_name'])) {
462 $file = @fopen
($this->_upload_manager
->files
[$elname]['tmp_name'], "rb");
464 while (!feof($file)) {
465 $data .= fread($file, 1024); // TODO: do we really have to do this?
478 //finalize the form definition if not yet done
479 if (!$this->_definition_finalized
) {
480 $this->_definition_finalized
= true;
481 $this->definition_after_data();
483 $this->_form
->display();
487 * Abstract method - always override!
489 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
491 function definition() {
492 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
496 * Dummy stub method - override if you need to setup the form depending on current
497 * values. This method is called after definition(), data submission and set_data().
498 * All form setup that is dependent on form values should go in here.
500 function definition_after_data(){
504 * Dummy stub method - override if you needed to perform some extra validation.
505 * If there are errors return array of errors ("fieldname"=>"error message"),
506 * otherwise true if ok.
508 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
510 * @param array $data array of ("fieldname"=>value) of submitted data
511 * @param array $files array of uploaded files "element_name"=>tmp_file_path
512 * @return array of "element_name"=>"error_description" if there are errors,
513 * or an empty array if everything is OK (true allowed for backwards compatibility too).
515 function validation($data, $files) {
520 * Method to add a repeating group of elements to a form.
522 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
523 * @param integer $repeats no of times to repeat elements initially
524 * @param array $options Array of options to apply to elements. Array keys are element names.
525 * This is an array of arrays. The second sets of keys are the option types
527 * 'default' - default value is value
528 * 'type' - PARAM_* constant is value
529 * 'helpbutton' - helpbutton params array is value
530 * 'disabledif' - last three moodleform::disabledIf()
531 * params are value as an array
532 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
533 * @param string $addfieldsname name for button to add more fields
534 * @param int $addfieldsno how many fields to add at a time
535 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
536 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
537 * @return int no of repeats of element in this page
539 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
540 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
541 if ($addstring===null){
542 $addstring = get_string('addfields', 'form', $addfieldsno);
544 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
546 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT
);
547 $addfields = optional_param($addfieldsname, '', PARAM_TEXT
);
548 if (!empty($addfields)){
549 $repeats +
= $addfieldsno;
551 $mform =& $this->_form
;
552 $mform->registerNoSubmitButton($addfieldsname);
553 $mform->addElement('hidden', $repeathiddenname, $repeats);
554 //value not to be overridden by submitted value
555 $mform->setConstants(array($repeathiddenname=>$repeats));
556 for ($i=0; $i<$repeats; $i++
) {
557 foreach ($elementobjs as $elementobj){
558 $elementclone = clone($elementobj);
559 $name = $elementclone->getName();
561 $elementclone->setName($name."[$i]");
563 if (is_a($elementclone, 'HTML_QuickForm_header')){
564 $value=$elementclone->_text
;
565 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
568 $value=$elementclone->getLabel();
569 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
573 $mform->addElement($elementclone);
576 for ($i=0; $i<$repeats; $i++
) {
577 foreach ($options as $elementname => $elementoptions){
578 $pos=strpos($elementname, '[');
580 $realelementname = substr($elementname, 0, $pos+
1)."[$i]";
581 $realelementname .= substr($elementname, $pos+
1);
583 $realelementname = $elementname."[$i]";
585 foreach ($elementoptions as $option => $params){
589 $mform->setDefault($realelementname, $params);
592 $mform->setHelpButton($realelementname, $params);
595 $params = array_merge(array($realelementname), $params);
596 call_user_func_array(array(&$mform, 'disabledIf'), $params);
599 if (is_string($params)){
600 $params = array(null, $params, null, 'client');
602 $params = array_merge(array($realelementname), $params);
603 call_user_func_array(array(&$mform, 'addRule'), $params);
610 $mform->addElement('submit', $addfieldsname, $addstring);
612 if (!$addbuttoninside) {
613 $mform->closeHeaderBefore($addfieldsname);
620 * Adds a link/button that controls the checked state of a group of checkboxes.
621 * @param int $groupid The id of the group of advcheckboxes this element controls
622 * @param string $text The text of the link. Defaults to "select all/none"
623 * @param array $attributes associative array of HTML attributes
624 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
626 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
629 $text = get_string('selectallornone', 'form');
632 $mform = $this->_form
;
633 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT
);
635 if ($select_value == 0 ||
is_null($select_value)) {
636 $new_select_value = 1;
638 $new_select_value = 0;
641 $mform->addElement('hidden', "checkbox_controller$groupid");
642 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
644 // Locate all checkboxes for this group and set their value, IF the optional param was given
645 if (!is_null($select_value)) {
646 foreach ($this->_form
->_elements
as $element) {
647 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
648 $mform->setConstants(array($element->getAttribute('name') => $select_value));
653 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
654 $mform->registerNoSubmitButton($checkbox_controller_name);
656 // Prepare Javascript for submit element
657 $js = "\n//<![CDATA[\n";
658 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
660 function html_quickform_toggle_checkboxes(group) {
661 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
662 var newvalue = false;
663 var global = eval('html_quickform_checkboxgroup' + group + ';');
665 eval('html_quickform_checkboxgroup' + group + ' = 0;');
668 eval('html_quickform_checkboxgroup' + group + ' = 1;');
669 newvalue = 'checked';
672 for (i = 0; i < checkboxes.length; i++) {
673 checkboxes[i].checked = newvalue;
677 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
679 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
683 require_once("$CFG->libdir/form/submitlink.php");
684 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
685 $submitlink->_js
= $js;
686 $submitlink->_onclick
= "html_quickform_toggle_checkboxes($groupid); return false;";
687 $mform->addElement($submitlink);
688 $mform->setDefault($checkbox_controller_name, $text);
692 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
693 * if you don't want a cancel button in your form. If you have a cancel button make sure you
694 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
695 * get data with get_data().
697 * @param boolean $cancel whether to show cancel button, default true
698 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
700 function add_action_buttons($cancel = true, $submitlabel=null){
701 if (is_null($submitlabel)){
702 $submitlabel = get_string('savechanges');
704 $mform =& $this->_form
;
706 //when two elements we need a group
707 $buttonarray=array();
708 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
709 $buttonarray[] = &$mform->createElement('cancel');
710 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
711 $mform->closeHeaderBefore('buttonar');
714 $mform->addElement('submit', 'submitbutton', $submitlabel);
715 $mform->closeHeaderBefore('submitbutton');
721 * You never extend this class directly. The class methods of this class are available from
722 * the private $this->_form property on moodleform and its children. You generally only
723 * call methods on this class from within abstract methods that you override on moodleform such
724 * as definition and definition_after_data
727 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
728 var $_types = array();
729 var $_dependencies = array();
731 * Array of buttons that if pressed do not result in the processing of the form.
735 var $_noSubmitButtons=array();
737 * Array of buttons that if pressed do not result in the processing of the form.
741 var $_cancelButtons=array();
744 * Array whose keys are element names. If the key exists this is a advanced element
748 var $_advancedElements = array();
751 * Whether to display advanced elements (on page load)
755 var $_showAdvanced = null;
758 * The form name is derrived from the class name of the wrapper minus the trailing form
759 * It is a name with words joined by underscores whereas the id attribute is words joined by
767 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
771 var $_pageparams = '';
774 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
775 * @param string $formName Form's name.
776 * @param string $method (optional)Form's method defaults to 'POST'
777 * @param mixed $action (optional)Form's action - string or moodle_url
778 * @param string $target (optional)Form's target defaults to none
779 * @param mixed $attributes (optional)Extra attributes for <form> tag
780 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
783 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
786 static $formcounter = 1;
788 HTML_Common
::HTML_Common($attributes);
789 $target = empty($target) ?
array() : array('target' => $target);
790 $this->_formName
= $formName;
791 if (is_a($action, 'moodle_url')){
792 $this->_pageparams
= $action->hidden_params_out();
793 $action = $action->out(true);
795 $this->_pageparams
= '';
797 //no 'name' atttribute for form in xhtml strict :
798 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) +
$target;
800 $this->updateAttributes($attributes);
802 //this is custom stuff for Moodle :
803 $oldclass= $this->getAttribute('class');
804 if (!empty($oldclass)){
805 $this->updateAttributes(array('class'=>$oldclass.' mform'));
807 $this->updateAttributes(array('class'=>'mform'));
809 $this->_reqHTML
= '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />';
810 $this->_advancedHTML
= '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath
.'/adv.gif'.'" />';
811 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />'));
812 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
816 * Use this method to indicate an element in a form is an advanced field. If items in a form
817 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
818 * form so the user can decide whether to display advanced form controls.
820 * If you set a header element to advanced then all elements it contains will also be set as advanced.
822 * @param string $elementName group or element name (not the element name of something inside a group).
823 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
825 function setAdvanced($elementName, $advanced=true){
827 $this->_advancedElements
[$elementName]='';
828 } elseif (isset($this->_advancedElements
[$elementName])) {
829 unset($this->_advancedElements
[$elementName]);
831 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
832 $this->setShowAdvanced();
833 $this->registerNoSubmitButton('mform_showadvanced');
835 $this->addElement('hidden', 'mform_showadvanced_last');
839 * Set whether to show advanced elements in the form on first displaying form. Default is not to
840 * display advanced elements in the form until 'Show Advanced' is pressed.
842 * You can get the last state of the form and possibly save it for this user by using
843 * value 'mform_showadvanced_last' in submitted data.
845 * @param boolean $showadvancedNow
847 function setShowAdvanced($showadvancedNow = null){
848 if ($showadvancedNow === null){
849 if ($this->_showAdvanced
!== null){
851 } else { //if setShowAdvanced is called without any preference
852 //make the default to not show advanced elements.
853 $showadvancedNow = get_user_preferences(
854 moodle_strtolower($this->_formName
.'_showadvanced', 0));
857 //value of hidden element
858 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT
);
860 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW
);
861 //toggle if button pressed or else stay the same
862 if ($hiddenLast == -1) {
863 $next = $showadvancedNow;
864 } elseif ($buttonPressed) { //toggle on button press
865 $next = !$hiddenLast;
869 $this->_showAdvanced
= $next;
870 if ($showadvancedNow != $next){
871 set_user_preference($this->_formName
.'_showadvanced', $next);
873 $this->setConstants(array('mform_showadvanced_last'=>$next));
875 function getShowAdvanced(){
876 return $this->_showAdvanced
;
883 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
888 function accept(&$renderer) {
889 if (method_exists($renderer, 'setAdvancedElements')){
890 //check for visible fieldsets where all elements are advanced
891 //and mark these headers as advanced as well.
892 //And mark all elements in a advanced header as advanced
893 $stopFields = $renderer->getStopFieldSetElements();
895 $lastHeaderAdvanced = false;
896 $anyAdvanced = false;
897 foreach (array_keys($this->_elements
) as $elementIndex){
898 $element =& $this->_elements
[$elementIndex];
900 // if closing header and any contained element was advanced then mark it as advanced
901 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
902 if ($anyAdvanced && !is_null($lastHeader)){
903 $this->setAdvanced($lastHeader->getName());
905 $lastHeaderAdvanced = false;
908 } elseif ($lastHeaderAdvanced) {
909 $this->setAdvanced($element->getName());
912 if ($element->getType()=='header'){
913 $lastHeader =& $element;
914 $anyAdvanced = false;
915 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
916 } elseif (isset($this->_advancedElements
[$element->getName()])){
920 // the last header may not be closed yet...
921 if ($anyAdvanced && !is_null($lastHeader)){
922 $this->setAdvanced($lastHeader->getName());
924 $renderer->setAdvancedElements($this->_advancedElements
);
927 parent
::accept($renderer);
932 function closeHeaderBefore($elementName){
933 $renderer =& $this->defaultRenderer();
934 $renderer->addStopFieldsetElements($elementName);
938 * Should be used for all elements of a form except for select, radio and checkboxes which
939 * clean their own data.
941 * @param string $elementname
942 * @param integer $paramtype use the constants PARAM_*.
943 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
944 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
945 * It will strip all html tags. But will still let tags for multilang support
947 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
948 * html editor. Data from the editor is later cleaned before display using
949 * format_text() function. PARAM_RAW can also be used for data that is validated
950 * by some other way or printed by p() or s().
951 * * PARAM_INT should be used for integers.
952 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
955 function setType($elementname, $paramtype) {
956 $this->_types
[$elementname] = $paramtype;
960 * See description of setType above. This can be used to set several types at once.
962 * @param array $paramtypes
964 function setTypes($paramtypes) {
965 $this->_types
= $paramtypes +
$this->_types
;
968 function updateSubmission($submission, $files) {
969 $this->_flagSubmitted
= false;
971 if (empty($submission)) {
972 $this->_submitValues
= array();
974 foreach ($submission as $key=>$s) {
975 if (array_key_exists($key, $this->_types
)) {
976 $submission[$key] = clean_param($s, $this->_types
[$key]);
979 $this->_submitValues
= $this->_recursiveFilter('stripslashes', $submission);
980 $this->_flagSubmitted
= true;
984 $this->_submitFiles
= array();
986 if (1 == get_magic_quotes_gpc()) {
987 foreach (array_keys($files) as $elname) {
988 // dangerous characters in filenames are cleaned later in upload_manager
989 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
992 $this->_submitFiles
= $files;
993 $this->_flagSubmitted
= true;
996 // need to tell all elements that they need to update their value attribute.
997 foreach (array_keys($this->_elements
) as $key) {
998 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
1002 function getReqHTML(){
1003 return $this->_reqHTML
;
1006 function getAdvancedHTML(){
1007 return $this->_advancedHTML
;
1011 * Initializes a default form value. Used to specify the default for a new entry where
1012 * no data is loaded in using moodleform::set_data()
1014 * @param string $elementname element name
1015 * @param mixed $values values for that element name
1016 * @param bool $slashed the default value is slashed
1020 function setDefault($elementName, $defaultValue, $slashed=false){
1021 $filter = $slashed ?
'stripslashes' : NULL;
1022 $this->setDefaults(array($elementName=>$defaultValue), $filter);
1023 } // end func setDefault
1025 * Add an array of buttons to the form
1026 * @param array $buttons An associative array representing help button to attach to
1027 * to the form. keys of array correspond to names of elements in form.
1031 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1033 foreach ($buttons as $elementname => $button){
1034 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1038 * Add a single button.
1040 * @param string $elementname name of the element to add the item to
1041 * @param array $button - arguments to pass to function $function
1042 * @param boolean $suppresscheck - whether to throw an error if the element
1044 * @param string $function - function to generate html from the arguments in $button
1046 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
1047 if (array_key_exists($elementname, $this->_elementIndex
)){
1048 //_elements has a numeric index, this code accesses the elements by name
1049 $element=&$this->_elements
[$this->_elementIndex
[$elementname]];
1050 if (method_exists($element, 'setHelpButton')){
1051 $element->setHelpButton($button, $function);
1054 $a->name
=$element->getName();
1055 $a->classname
=get_class($element);
1056 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
1058 }elseif (!$suppresscheck){
1059 print_error('nonexistentformelements', 'form', '', $elementname);
1063 function exportValues($elementList= null, $addslashes=true){
1064 $unfiltered = array();
1065 if (null === $elementList) {
1066 // iterate over all elements, calling their exportValue() methods
1067 $emptyarray = array();
1068 foreach (array_keys($this->_elements
) as $key) {
1069 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
){
1070 $value = $this->_elements
[$key]->exportValue($emptyarray, true);
1072 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
1075 if (is_array($value)) {
1076 // This shit throws a bogus warning in PHP 4.3.x
1077 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
1081 if (!is_array($elementList)) {
1082 $elementList = array_map('trim', explode(',', $elementList));
1084 foreach ($elementList as $elementName) {
1085 $value = $this->exportValue($elementName);
1086 if (PEAR
::isError($value)) {
1089 $unfiltered[$elementName] = $value;
1094 return $this->_recursiveFilter('addslashes', $unfiltered);
1100 * Adds a validation rule for the given field
1102 * If the element is in fact a group, it will be considered as a whole.
1103 * To validate grouped elements as separated entities,
1104 * use addGroupRule instead of addRule.
1106 * @param string $element Form element name
1107 * @param string $message Message to display for invalid data
1108 * @param string $type Rule type, use getRegisteredRules() to get types
1109 * @param string $format (optional)Required for extra rule data
1110 * @param string $validation (optional)Where to perform validation: "server", "client"
1111 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1112 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1115 * @throws HTML_QuickForm_Error
1117 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1119 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
1120 if ($validation == 'client') {
1121 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1124 } // end func addRule
1126 * Adds a validation rule for the given group of elements
1128 * Only groups with a name can be assigned a validation rule
1129 * Use addGroupRule when you need to validate elements inside the group.
1130 * Use addRule if you need to validate the group as a whole. In this case,
1131 * the same rule will be applied to all elements in the group.
1132 * Use addRule if you need to validate the group against a function.
1134 * @param string $group Form group name
1135 * @param mixed $arg1 Array for multiple elements or error message string for one element
1136 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1137 * @param string $format (optional)Required for extra rule data
1138 * @param int $howmany (optional)How many valid elements should be in the group
1139 * @param string $validation (optional)Where to perform validation: "server", "client"
1140 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1143 * @throws HTML_QuickForm_Error
1145 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1147 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1148 if (is_array($arg1)) {
1149 foreach ($arg1 as $rules) {
1150 foreach ($rules as $rule) {
1151 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
1153 if ('client' == $validation) {
1154 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1158 } elseif (is_string($arg1)) {
1160 if ($validation == 'client') {
1161 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1164 } // end func addGroupRule
1168 * Returns the client side validation script
1170 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1171 * and slightly modified to run rules per-element
1172 * Needed to override this because of an error with client side validation of grouped elements.
1175 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1177 function getValidationScript()
1179 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1183 include_once('HTML/QuickForm/RuleRegistry.php');
1184 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1195 foreach ($this->_rules
as $elementName => $rules) {
1196 foreach ($rules as $rule) {
1197 if ('client' == $rule['validation']) {
1198 unset($element); //TODO: find out how to properly initialize it
1200 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1201 $rule['message'] = strtr($rule['message'], $js_escape);
1203 if (isset($rule['group'])) {
1204 $group =& $this->getElement($rule['group']);
1205 // No JavaScript validation for frozen elements
1206 if ($group->isFrozen()) {
1209 $elements =& $group->getElements();
1210 foreach (array_keys($elements) as $key) {
1211 if ($elementName == $group->getElementName($key)) {
1212 $element =& $elements[$key];
1216 } elseif ($dependent) {
1218 $element[] =& $this->getElement($elementName);
1219 foreach ($rule['dependent'] as $elName) {
1220 $element[] =& $this->getElement($elName);
1223 $element =& $this->getElement($elementName);
1225 // No JavaScript validation for frozen elements
1226 if (is_object($element) && $element->isFrozen()) {
1228 } elseif (is_array($element)) {
1229 foreach (array_keys($element) as $key) {
1230 if ($element[$key]->isFrozen()) {
1235 // Fix for bug displaying errors for elements in a group
1236 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1237 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1238 $test[$elementName][1]=$element;
1244 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1245 // the form, and then that form field gets corrupted by the code that follows.
1249 <script type="text/javascript">
1252 var skipClientValidation = false;
1254 function qf_errorHandler(element, _qfMsg) {
1255 div = element.parentNode;
1256 if (_qfMsg != \'\') {
1257 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1259 errorSpan = document.createElement("span");
1260 errorSpan.id = \'id_error_\'+element.name;
1261 errorSpan.className = "error";
1262 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1265 while (errorSpan.firstChild) {
1266 errorSpan.removeChild(errorSpan.firstChild);
1269 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1270 errorSpan.appendChild(document.createElement("br"));
1272 if (div.className.substr(div.className.length - 6, 6) != " error"
1273 && div.className != "error") {
1274 div.className += " error";
1279 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1281 errorSpan.parentNode.removeChild(errorSpan);
1284 if (div.className.substr(div.className.length - 6, 6) == " error") {
1285 div.className = div.className.substr(0, div.className.length - 6);
1286 } else if (div.className == "error") {
1294 foreach ($test as $elementName => $jsandelement) {
1295 // Fix for bug displaying errors for elements in a group
1297 list($jsArr,$element)=$jsandelement;
1300 function validate_' . $this->_formName
. '_' . $elementName . '(element) {
1302 var errFlag = new Array();
1305 var frm = element.parentNode;
1306 while (frm && frm.nodeName != "FORM") {
1307 frm = frm.parentNode;
1309 ' . join("\n", $jsArr) . '
1310 return qf_errorHandler(element, _qfMsg);
1314 ret = validate_' . $this->_formName
. '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1315 if (!ret && !first_focus) {
1317 frm.elements[\''.$elementName.'\'].focus();
1321 // Fix for bug displaying errors for elements in a group
1323 //$element =& $this->getElement($elementName);
1325 $valFunc = 'validate_' . $this->_formName
. '_' . $elementName . '(this)';
1326 $onBlur = $element->getAttribute('onBlur');
1327 $onChange = $element->getAttribute('onChange');
1328 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1329 'onChange' => $onChange . $valFunc));
1331 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1333 function validate_' . $this->_formName
. '(frm) {
1334 if (skipClientValidation) {
1339 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1340 var first_focus = false;
1341 ' . $validateJS . ';
1347 } // end func getValidationScript
1348 function _setDefaultRuleMessages(){
1349 foreach ($this->_rules
as $field => $rulesarr){
1350 foreach ($rulesarr as $key => $rule){
1351 if ($rule['message']===null){
1353 $a->format
=$rule['format'];
1354 $str=get_string('err_'.$rule['type'], 'form', $a);
1355 if (strpos($str, '[[')!==0){
1356 $this->_rules
[$field][$key]['message']=$str;
1363 function getLockOptionEndScript(){
1365 $iname = $this->getAttribute('id').'items';
1366 $js = '<script type="text/javascript">'."\n";
1367 $js .= '//<![CDATA['."\n";
1368 $js .= "var $iname = Array();\n";
1370 foreach ($this->_dependencies
as $dependentOn => $conditions){
1371 $js .= "{$iname}['$dependentOn'] = Array();\n";
1372 foreach ($conditions as $condition=>$values) {
1373 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1374 foreach ($values as $value=>$dependents) {
1375 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1377 foreach ($dependents as $dependent) {
1378 $elements = $this->_getElNamesRecursive($dependent);
1379 if (empty($elements)) {
1380 // probably element inside of some group
1381 $elements = array($dependent);
1383 foreach($elements as $element) {
1384 if ($element == $dependentOn) {
1387 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1394 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1396 $js .='</script>'."\n";
1400 function _getElNamesRecursive($element) {
1401 if (is_string($element)) {
1402 if (!$this->elementExists($element)) {
1405 $element = $this->getElement($element);
1408 if (is_a($element, 'HTML_QuickForm_group')) {
1409 $elsInGroup = $element->getElements();
1411 foreach ($elsInGroup as $elInGroup){
1412 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1413 // not sure if this would work - groups nested in groups
1414 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1416 $elNames[] = $element->getElementName($elInGroup->getName());
1420 } else if (is_a($element, 'HTML_QuickForm_header')) {
1423 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1426 } else if (method_exists($element, 'getPrivateName')) {
1427 return array($element->getPrivateName());
1430 $elNames = array($element->getName());
1437 * Adds a dependency for $elementName which will be disabled if $condition is met.
1438 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1439 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1440 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1441 * of the $dependentOn element is $condition (such as equal) to $value.
1443 * @param string $elementName the name of the element which will be disabled
1444 * @param string $dependentOn the name of the element whose state will be checked for
1446 * @param string $condition the condition to check
1447 * @param mixed $value used in conjunction with condition.
1449 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1450 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
1451 $this->_dependencies
[$dependentOn] = array();
1453 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
1454 $this->_dependencies
[$dependentOn][$condition] = array();
1456 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
1457 $this->_dependencies
[$dependentOn][$condition][$value] = array();
1459 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
1462 function registerNoSubmitButton($buttonname){
1463 $this->_noSubmitButtons
[]=$buttonname;
1466 function isNoSubmitButton($buttonname){
1467 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
1470 function _registerCancelButton($addfieldsname){
1471 $this->_cancelButtons
[]=$addfieldsname;
1474 * Displays elements without HTML input tags.
1475 * This method is different to freeze() in that it makes sure no hidden
1476 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1479 * This function also removes all previously defined rules.
1481 * @param mixed $elementList array or string of element(s) to be frozen
1484 * @throws HTML_QuickForm_Error
1486 function hardFreeze($elementList=null)
1488 if (!isset($elementList)) {
1489 $this->_freezeAll
= true;
1490 $elementList = array();
1492 if (!is_array($elementList)) {
1493 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1495 $elementList = array_flip($elementList);
1498 foreach (array_keys($this->_elements
) as $key) {
1499 $name = $this->_elements
[$key]->getName();
1500 if ($this->_freezeAll ||
isset($elementList[$name])) {
1501 $this->_elements
[$key]->freeze();
1502 $this->_elements
[$key]->setPersistantFreeze(false);
1503 unset($elementList[$name]);
1506 $this->_rules
[$name] = array();
1507 // if field is required, remove the rule
1508 $unset = array_search($name, $this->_required
);
1509 if ($unset !== false) {
1510 unset($this->_required
[$unset]);
1515 if (!empty($elementList)) {
1516 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);
1521 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1523 * This function also removes all previously defined rules of elements it freezes.
1525 * @param array $elementList array or string of element(s) not to be frozen
1528 * @throws HTML_QuickForm_Error
1530 function hardFreezeAllVisibleExcept($elementList)
1532 $elementList = array_flip($elementList);
1533 foreach (array_keys($this->_elements
) as $key) {
1534 $name = $this->_elements
[$key]->getName();
1535 $type = $this->_elements
[$key]->getType();
1537 if ($type == 'hidden'){
1538 // leave hidden types as they are
1539 } elseif (!isset($elementList[$name])) {
1540 $this->_elements
[$key]->freeze();
1541 $this->_elements
[$key]->setPersistantFreeze(false);
1544 $this->_rules
[$name] = array();
1545 // if field is required, remove the rule
1546 $unset = array_search($name, $this->_required
);
1547 if ($unset !== false) {
1548 unset($this->_required
[$unset]);
1555 * Tells whether the form was already submitted
1557 * This is useful since the _submitFiles and _submitValues arrays
1558 * may be completely empty after the trackSubmit value is removed.
1563 function isSubmitted()
1565 return parent
::isSubmitted() && (!$this->isFrozen());
1571 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1572 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1574 * Stylesheet is part of standard theme and should be automatically included.
1576 * @author Jamie Pratt <me@jamiep.org>
1577 * @license gpl license
1579 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
1582 * Element template array
1586 var $_elementTemplates;
1588 * Template used when opening a hidden fieldset
1589 * (i.e. a fieldset that is opened when there is no header element)
1593 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1595 * Header Template string
1599 var $_headerTemplate =
1600 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1603 * Template used when opening a fieldset
1607 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1610 * Template used when closing a fieldset
1614 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1617 * Required Note template string
1621 var $_requiredNoteTemplate =
1622 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1624 var $_advancedElements = array();
1627 * Whether to display advanced elements (on page load)
1629 * @var integer 1 means show 0 means hide
1633 function MoodleQuickForm_Renderer(){
1634 // switch next two lines for ol li containers for form items.
1635 // $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>');
1636 $this->_elementTemplates
= array(
1637 '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>',
1639 '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>',
1641 '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>',
1645 parent
::HTML_QuickForm_Renderer_Tableless();
1648 function setAdvancedElements($elements){
1649 $this->_advancedElements
= $elements;
1653 * What to do when starting the form
1655 * @param MoodleQuickForm $form
1657 function startForm(&$form){
1658 $this->_reqHTML
= $form->getReqHTML();
1659 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
1660 $this->_advancedHTML
= $form->getAdvancedHTML();
1661 $this->_showAdvanced
= $form->getShowAdvanced();
1662 parent
::startForm($form);
1663 if ($form->isFrozen()){
1664 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
1666 $this->_hiddenHtml
.= $form->_pageparams
;
1672 function startGroup(&$group, $required, $error){
1673 if (method_exists($group, 'getElementTemplateType')){
1674 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
1676 $html = $this->_elementTemplates
['default'];
1679 if ($this->_showAdvanced
){
1680 $advclass = ' advanced';
1682 $advclass = ' advanced hide';
1684 if (isset($this->_advancedElements
[$group->getName()])){
1685 $html =str_replace(' {advanced}', $advclass, $html);
1686 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1688 $html =str_replace(' {advanced}', '', $html);
1689 $html =str_replace('{advancedimg}', '', $html);
1691 if (method_exists($group, 'getHelpButton')){
1692 $html =str_replace('{help}', $group->getHelpButton(), $html);
1694 $html =str_replace('{help}', '', $html);
1696 $html =str_replace('{name}', $group->getName(), $html);
1697 $html =str_replace('{type}', 'fgroup', $html);
1699 $this->_templates
[$group->getName()]=$html;
1700 // Fix for bug in tableless quickforms that didn't allow you to stop a
1701 // fieldset before a group of elements.
1702 // if the element name indicates the end of a fieldset, close the fieldset
1703 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
1704 && $this->_fieldsetsOpen
> 0
1706 $this->_html
.= $this->_closeFieldsetTemplate
;
1707 $this->_fieldsetsOpen
--;
1709 parent
::startGroup($group, $required, $error);
1712 function renderElement(&$element, $required, $error){
1713 //manipulate id of all elements before rendering
1714 if (!is_null($element->getAttribute('id'))) {
1715 $id = $element->getAttribute('id');
1717 $id = $element->getName();
1719 //strip qf_ prefix and replace '[' with '_' and strip ']'
1720 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1721 if (strpos($id, 'id_') !== 0){
1722 $element->updateAttributes(array('id'=>'id_'.$id));
1725 //adding stuff to place holders in template
1726 if (method_exists($element, 'getElementTemplateType')){
1727 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
1729 $html = $this->_elementTemplates
['default'];
1731 if ($this->_showAdvanced
){
1732 $advclass = ' advanced';
1734 $advclass = ' advanced hide';
1736 if (isset($this->_advancedElements
[$element->getName()])){
1737 $html =str_replace(' {advanced}', $advclass, $html);
1739 $html =str_replace(' {advanced}', '', $html);
1741 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
1742 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1744 $html =str_replace('{advancedimg}', '', $html);
1746 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1747 $html =str_replace('{name}', $element->getName(), $html);
1748 if (method_exists($element, 'getHelpButton')){
1749 $html = str_replace('{help}', $element->getHelpButton(), $html);
1751 $html = str_replace('{help}', '', $html);
1754 if (!isset($this->_templates
[$element->getName()])) {
1755 $this->_templates
[$element->getName()] = $html;
1758 parent
::renderElement($element, $required, $error);
1761 function finishForm(&$form){
1762 if ($form->isFrozen()){
1763 $this->_hiddenHtml
= '';
1765 parent
::finishForm($form);
1766 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1767 // add a lockoptions script
1768 $this->_html
= $this->_html
. "\n" . $script;
1772 * Called when visiting a header element
1774 * @param object An HTML_QuickForm_header element being visited
1778 function renderHeader(&$header) {
1779 $name = $header->getName();
1781 $id = empty($name) ?
'' : ' id="' . $name . '"';
1782 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1783 if (is_null($header->_text
)) {
1785 } elseif (!empty($name) && isset($this->_templates
[$name])) {
1786 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
1788 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
1791 if (isset($this->_advancedElements
[$name])){
1792 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
1794 $header_html =str_replace('{advancedimg}', '', $header_html);
1796 $elementName='mform_showadvanced';
1797 if ($this->_showAdvanced
==0){
1798 $buttonlabel = get_string('showadvanced', 'form');
1800 $buttonlabel = get_string('hideadvanced', 'form');
1803 if (isset($this->_advancedElements
[$name])){
1804 // this is tricky - the first submit button on form is "clicked" if user presses enter
1805 // we do not want to "submit" using advanced button if javascript active
1806 $showtext="'".get_string('showadvanced', 'form')."'";
1807 $hidetext="'".get_string('hideadvanced', 'form')."'";
1808 //onclick returns false so if js is on then page is not submitted.
1809 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1810 $button_js = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="button" onclick="'.$onclick.'" />';
1811 $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />';
1812 $button = '<script type="text/javascript">
1814 document.write("'.addslashes_js($button_js).'")
1816 </script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation
1818 $header_html = str_replace('{button}', $button, $header_html);
1820 $header_html = str_replace('{button}', '', $header_html);
1823 if ($this->_fieldsetsOpen
> 0) {
1824 $this->_html
.= $this->_closeFieldsetTemplate
;
1825 $this->_fieldsetsOpen
--;
1828 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
1829 if ($this->_showAdvanced
){
1830 $advclass = ' class="advanced"';
1832 $advclass = ' class="advanced hide"';
1834 if (isset($this->_advancedElements
[$name])){
1835 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1837 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1839 $this->_html
.= $openFieldsetTemplate . $header_html;
1840 $this->_fieldsetsOpen++
;
1841 } // end func renderHeader
1843 function getStopFieldsetElements(){
1844 return $this->_stopFieldsetElements
;
1849 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1851 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1852 MoodleQuickForm
::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1853 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1854 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1855 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1856 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1857 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1858 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1859 MoodleQuickForm
::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
1860 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1861 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1862 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1863 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1864 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1865 MoodleQuickForm
::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1866 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1867 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1868 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1869 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1870 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1871 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1872 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1873 MoodleQuickForm
::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1874 MoodleQuickForm
::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1875 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1876 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1877 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1878 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
1879 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');