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
->setType('sesskey', PARAM_RAW
);
120 $this->_form
->setDefault('sesskey', sesskey());
121 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
122 $this->_form
->setType('_qf__'.$this->_formname
, PARAM_RAW
);
123 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
124 $this->_form
->_setDefaultRuleMessages();
126 // we have to know all input types before processing submission ;-)
127 $this->_process_submission($method);
131 * To autofocus on first form element or first element with error.
133 * @param string $name if this is set then the focus is forced to a field with this name
135 * @return string javascript to select form element with first error or
136 * first element if no errors. Use this as a parameter
137 * when calling print_header
139 function focus($name=NULL) {
140 $form =& $this->_form
;
141 $elkeys = array_keys($form->_elementIndex
);
143 if (isset($form->_errors
) && 0 != count($form->_errors
)){
144 $errorkeys = array_keys($form->_errors
);
145 $elkeys = array_intersect($elkeys, $errorkeys);
149 if ($error or empty($name)) {
151 while (empty($names) and !empty($elkeys)) {
152 $el = array_shift($elkeys);
153 $names = $form->_getElNamesRecursive($el);
155 if (!empty($names)) {
156 $name = array_shift($names);
162 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
169 * Internal method. Alters submitted data to be suitable for quickforms processing.
170 * Must be called when the form is fully set up.
172 function _process_submission($method) {
173 $submission = array();
174 if ($method == 'post') {
175 if (!empty($_POST)) {
176 $submission = $_POST;
179 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
182 // following trick is needed to enable proper sesskey checks when using GET forms
183 // the _qf__.$this->_formname serves as a marker that form was actually submitted
184 if (array_key_exists('_qf__'.$this->_formname
, $submission) and $submission['_qf__'.$this->_formname
] == 1) {
185 if (!confirm_sesskey()) {
186 print_error('invalidsesskey');
190 $submission = array();
194 $this->_form
->updateSubmission($submission, $files);
198 * Internal method. Validates all uploaded files.
200 function _validate_files(&$files) {
203 if (empty($_FILES)) {
204 // we do not need to do any checks because no files were submitted
205 // note: server side rules do not work for files - use custom verification in validate() instead
209 $mform =& $this->_form
;
212 $status = $this->_upload_manager
->preprocess_files();
214 // now check that we really want each file
215 foreach ($_FILES as $elname=>$file) {
216 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
217 $required = $mform->isElementRequired($elname);
218 if (!empty($this->_upload_manager
->files
[$elname]['uploadlog']) and empty($this->_upload_manager
->files
[$elname]['clear'])) {
219 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE
) {
220 // file not uploaded and not required - ignore it
223 $errors[$elname] = $this->_upload_manager
->files
[$elname]['uploadlog'];
225 } else if (!empty($this->_upload_manager
->files
[$elname]['clear'])) {
226 $files[$elname] = $this->_upload_manager
->files
[$elname]['tmp_name'];
229 error('Incorrect upload attempt!');
233 // return errors if found
234 if ($status and 0 == count($errors)){
244 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
245 * form definition (new entry form); this function is used to load in data where values
246 * already exist and data is being edited (edit entry form).
248 * @param mixed $default_values object or array of default values
249 * @param bool $slased true if magic quotes applied to data values
251 function set_data($default_values, $slashed=false) {
252 if (is_object($default_values)) {
253 $default_values = (array)$default_values;
255 $filter = $slashed ?
'stripslashes' : NULL;
256 $this->_form
->setDefaults($default_values, $filter);
260 * Set custom upload manager.
261 * Must be used BEFORE creating of file element!
263 * @param object $um - custom upload manager
265 function set_upload_manager($um=false) {
267 $um = new upload_manager();
269 $this->_upload_manager
= $um;
271 $this->_form
->setMaxFileSize($um->config
->maxbytes
);
275 * Check that form was submitted. Does not check validity of submitted data.
277 * @return bool true if form properly submitted
279 function is_submitted() {
280 return $this->_form
->isSubmitted();
283 function no_submit_button_pressed(){
284 static $nosubmit = null; // one check is enough
285 if (!is_null($nosubmit)){
288 $mform =& $this->_form
;
290 if (!$this->is_submitted()){
293 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
294 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
304 * Check that form data is valid.
305 * You should almost always use this, rather than {@see validate_defined_fields}
307 * @return bool true if form data valid
309 function is_validated() {
310 //finalize the form definition before any processing
311 if (!$this->_definition_finalized
) {
312 $this->_definition_finalized
= true;
313 $this->definition_after_data();
315 return $this->validate_defined_fields();
321 * You almost always want to call {@see is_validated} instead of this
322 * because it calls {@see definition_after_data} first, before validating the form,
323 * which is what you want in 99% of cases.
325 * This is provided as a separate function for those special cases where
326 * you want the form validated before definition_after_data is called
327 * for example, to selectively add new elements depending on a no_submit_button press,
328 * but only when the form is valid when the no_submit_button is pressed,
330 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
331 * is NOT to validate the form when a no submit button has been pressed.
332 * pass true here to override this behaviour
334 * @return bool true if form data valid
336 function validate_defined_fields($validateonnosubmit=false) {
337 static $validated = null; // one validation is enough
338 $mform =& $this->_form
;
340 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
342 } elseif ($validated === null) {
343 $internal_val = $mform->validate();
346 $file_val = $this->_validate_files($files);
347 if ($file_val !== true) {
348 if (!empty($file_val)) {
349 foreach ($file_val as $element=>$msg) {
350 $mform->setElementError($element, $msg);
356 $data = $mform->exportValues(null, true);
357 $moodle_val = $this->validation($data, $files);
358 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
359 // non-empty array means errors
360 foreach ($moodle_val as $element=>$msg) {
361 $mform->setElementError($element, $msg);
366 // anything else means validation ok
370 $validated = ($internal_val and $moodle_val and $file_val);
376 * Return true if a cancel button has been pressed resulting in the form being submitted.
378 * @return boolean true if a cancel button has been pressed
380 function is_cancelled(){
381 $mform =& $this->_form
;
382 if ($mform->isSubmitted()){
383 foreach ($mform->_cancelButtons
as $cancelbutton){
384 if (optional_param($cancelbutton, 0, PARAM_RAW
)){
393 * Return submitted data if properly submitted or returns NULL if validation fails or
394 * 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 valid or not submitted
399 function get_data($slashed=true) {
400 $mform =& $this->_form
;
402 if ($this->is_submitted() and $this->is_validated()) {
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 * Return submitted data without validation or NULL if there is no submitted data.
419 * @param bool $slashed true means return data with addslashes applied
420 * @return object submitted data; NULL if not submitted
422 function get_submitted_data($slashed=true) {
423 $mform =& $this->_form
;
425 if ($this->is_submitted()) {
426 $data = $mform->exportValues(null, $slashed);
427 unset($data['sesskey']); // we do not need to return sesskey
428 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
432 return (object)$data;
440 * Save verified uploaded files into directory. Upload process can be customised from definition()
441 * method by creating instance of upload manager and storing it in $this->_upload_form
443 * @param string $destination where to store uploaded files
444 * @return bool success
446 function save_files($destination) {
447 if ($this->is_submitted() and $this->is_validated()) {
448 return $this->_upload_manager
->save_files($destination);
454 * If we're only handling one file (if inputname was given in the constructor)
455 * this will return the (possibly changed) filename of the file.
456 * @return mixed false in case of failure, string if ok
458 function get_new_filename() {
459 return $this->_upload_manager
->get_new_filename();
463 * Get content of uploaded file.
464 * @param $element name of file upload element
465 * @return mixed false in case of failure, string if ok
467 function get_file_content($elname) {
468 if (!$this->is_submitted() or !$this->is_validated()) {
472 if (!$this->_form
->elementExists($elname)) {
476 if (empty($this->_upload_manager
->files
[$elname]['clear'])) {
480 if (empty($this->_upload_manager
->files
[$elname]['tmp_name'])) {
485 $file = @fopen
($this->_upload_manager
->files
[$elname]['tmp_name'], "rb");
487 while (!feof($file)) {
488 $data .= fread($file, 1024); // TODO: do we really have to do this?
501 //finalize the form definition if not yet done
502 if (!$this->_definition_finalized
) {
503 $this->_definition_finalized
= true;
504 $this->definition_after_data();
506 $this->_form
->display();
510 * Abstract method - always override!
512 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
514 function definition() {
515 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
519 * Dummy stub method - override if you need to setup the form depending on current
520 * values. This method is called after definition(), data submission and set_data().
521 * All form setup that is dependent on form values should go in here.
523 function definition_after_data(){
527 * Dummy stub method - override if you needed to perform some extra validation.
528 * If there are errors return array of errors ("fieldname"=>"error message"),
529 * otherwise true if ok.
531 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
533 * @param array $data array of ("fieldname"=>value) of submitted data
534 * @param array $files array of uploaded files "element_name"=>tmp_file_path
535 * @return array of "element_name"=>"error_description" if there are errors,
536 * or an empty array if everything is OK (true allowed for backwards compatibility too).
538 function validation($data, $files) {
543 * Method to add a repeating group of elements to a form.
545 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
546 * @param integer $repeats no of times to repeat elements initially
547 * @param array $options Array of options to apply to elements. Array keys are element names.
548 * This is an array of arrays. The second sets of keys are the option types
550 * 'default' - default value is value
551 * 'type' - PARAM_* constant is value
552 * 'helpbutton' - helpbutton params array is value
553 * 'disabledif' - last three moodleform::disabledIf()
554 * params are value as an array
555 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
556 * @param string $addfieldsname name for button to add more fields
557 * @param int $addfieldsno how many fields to add at a time
558 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
559 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
560 * @return int no of repeats of element in this page
562 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
563 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
564 if ($addstring===null){
565 $addstring = get_string('addfields', 'form', $addfieldsno);
567 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
569 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT
);
570 $addfields = optional_param($addfieldsname, '', PARAM_TEXT
);
571 if (!empty($addfields)){
572 $repeats +
= $addfieldsno;
574 $mform =& $this->_form
;
575 $mform->registerNoSubmitButton($addfieldsname);
576 $mform->addElement('hidden', $repeathiddenname, $repeats);
577 $mform->setType($repeathiddenname, PARAM_INT
);
578 //value not to be overridden by submitted value
579 $mform->setConstants(array($repeathiddenname=>$repeats));
580 $namecloned = array();
581 for ($i = 0; $i < $repeats; $i++
) {
582 foreach ($elementobjs as $elementobj){
583 $elementclone = fullclone($elementobj);
584 $name = $elementclone->getName();
585 $namecloned[] = $name;
587 $elementclone->setName($name."[$i]");
589 if (is_a($elementclone, 'HTML_QuickForm_header')) {
590 $value = $elementclone->_text
;
591 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
594 $value=$elementclone->getLabel();
595 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
599 $mform->addElement($elementclone);
602 for ($i=0; $i<$repeats; $i++
) {
603 foreach ($options as $elementname => $elementoptions){
604 $pos=strpos($elementname, '[');
606 $realelementname = substr($elementname, 0, $pos+
1)."[$i]";
607 $realelementname .= substr($elementname, $pos+
1);
609 $realelementname = $elementname."[$i]";
611 foreach ($elementoptions as $option => $params){
615 $mform->setDefault($realelementname, $params);
618 $mform->setHelpButton($realelementname, $params);
621 foreach ($namecloned as $num => $name){
622 if ($params[0] == $name){
623 $params[0] = $params[0]."[$i]";
627 $params = array_merge(array($realelementname), $params);
628 call_user_func_array(array(&$mform, 'disabledIf'), $params);
631 if (is_string($params)){
632 $params = array(null, $params, null, 'client');
634 $params = array_merge(array($realelementname), $params);
635 call_user_func_array(array(&$mform, 'addRule'), $params);
642 $mform->addElement('submit', $addfieldsname, $addstring);
644 if (!$addbuttoninside) {
645 $mform->closeHeaderBefore($addfieldsname);
652 * Adds a link/button that controls the checked state of a group of checkboxes.
653 * @param int $groupid The id of the group of advcheckboxes this element controls
654 * @param string $text The text of the link. Defaults to "select all/none"
655 * @param array $attributes associative array of HTML attributes
656 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
658 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
661 $text = get_string('selectallornone', 'form');
664 $mform = $this->_form
;
665 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT
);
667 if ($select_value == 0 ||
is_null($select_value)) {
668 $new_select_value = 1;
670 $new_select_value = 0;
673 $mform->addElement('hidden', "checkbox_controller$groupid");
674 $mform->setType("checkbox_controller$groupid", PARAM_INT
);
675 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
677 // Locate all checkboxes for this group and set their value, IF the optional param was given
678 if (!is_null($select_value)) {
679 foreach ($this->_form
->_elements
as $element) {
680 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
681 $mform->setConstants(array($element->getAttribute('name') => $select_value));
686 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
687 $mform->registerNoSubmitButton($checkbox_controller_name);
689 // Prepare Javascript for submit element
690 $js = "\n//<![CDATA[\n";
691 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
693 function html_quickform_toggle_checkboxes(group) {
694 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
695 var newvalue = false;
696 var global = eval('html_quickform_checkboxgroup' + group + ';');
698 eval('html_quickform_checkboxgroup' + group + ' = 0;');
701 eval('html_quickform_checkboxgroup' + group + ' = 1;');
702 newvalue = 'checked';
705 for (i = 0; i < checkboxes.length; i++) {
706 checkboxes[i].checked = newvalue;
710 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
712 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
716 require_once("$CFG->libdir/form/submitlink.php");
717 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
718 $submitlink->_js
= $js;
719 $submitlink->_onclick
= "html_quickform_toggle_checkboxes($groupid); return false;";
720 $mform->addElement($submitlink);
721 $mform->setDefault($checkbox_controller_name, $text);
725 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
726 * if you don't want a cancel button in your form. If you have a cancel button make sure you
727 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
728 * get data with get_data().
730 * @param boolean $cancel whether to show cancel button, default true
731 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
733 function add_action_buttons($cancel = true, $submitlabel=null){
734 if (is_null($submitlabel)){
735 $submitlabel = get_string('savechanges');
737 $mform =& $this->_form
;
739 //when two elements we need a group
740 $buttonarray=array();
741 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
742 $buttonarray[] = &$mform->createElement('cancel');
743 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
744 $mform->closeHeaderBefore('buttonar');
747 $mform->addElement('submit', 'submitbutton', $submitlabel);
748 $mform->closeHeaderBefore('submitbutton');
754 * You never extend this class directly. The class methods of this class are available from
755 * the private $this->_form property on moodleform and its children. You generally only
756 * call methods on this class from within abstract methods that you override on moodleform such
757 * as definition and definition_after_data
760 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
761 var $_types = array();
762 var $_dependencies = array();
764 * Array of buttons that if pressed do not result in the processing of the form.
768 var $_noSubmitButtons=array();
770 * Array of buttons that if pressed do not result in the processing of the form.
774 var $_cancelButtons=array();
777 * Array whose keys are element names. If the key exists this is a advanced element
781 var $_advancedElements = array();
784 * Whether to display advanced elements (on page load)
788 var $_showAdvanced = null;
791 * The form name is derrived from the class name of the wrapper minus the trailing form
792 * It is a name with words joined by underscores whereas the id attribute is words joined by
800 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
804 var $_pageparams = '';
807 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
808 * @param string $formName Form's name.
809 * @param string $method (optional)Form's method defaults to 'POST'
810 * @param mixed $action (optional)Form's action - string or moodle_url
811 * @param string $target (optional)Form's target defaults to none
812 * @param mixed $attributes (optional)Extra attributes for <form> tag
813 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
816 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
819 static $formcounter = 1;
821 HTML_Common
::HTML_Common($attributes);
822 $target = empty($target) ?
array() : array('target' => $target);
823 $this->_formName
= $formName;
824 if (is_a($action, 'moodle_url')){
825 $this->_pageparams
= $action->hidden_params_out();
826 $action = $action->out(true);
828 $this->_pageparams
= '';
830 //no 'name' atttribute for form in xhtml strict :
831 $attributes = array('action'=>$action, 'method'=>$method,
832 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) +
$target;
834 $this->updateAttributes($attributes);
836 //this is custom stuff for Moodle :
837 $oldclass= $this->getAttribute('class');
838 if (!empty($oldclass)){
839 $this->updateAttributes(array('class'=>$oldclass.' mform'));
841 $this->updateAttributes(array('class'=>'mform'));
843 $this->_reqHTML
= '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />';
844 $this->_advancedHTML
= '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath
.'/adv.gif'.'" />';
845 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath
.'/req.gif'.'" />'));
846 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
850 * Use this method to indicate an element in a form is an advanced field. If items in a form
851 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
852 * form so the user can decide whether to display advanced form controls.
854 * If you set a header element to advanced then all elements it contains will also be set as advanced.
856 * @param string $elementName group or element name (not the element name of something inside a group).
857 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
859 function setAdvanced($elementName, $advanced=true){
861 $this->_advancedElements
[$elementName]='';
862 } elseif (isset($this->_advancedElements
[$elementName])) {
863 unset($this->_advancedElements
[$elementName]);
865 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
866 $this->setShowAdvanced();
867 $this->registerNoSubmitButton('mform_showadvanced');
869 $this->addElement('hidden', 'mform_showadvanced_last');
870 $this->setType('mform_showadvanced_last', PARAM_INT
);
874 * Set whether to show advanced elements in the form on first displaying form. Default is not to
875 * display advanced elements in the form until 'Show Advanced' is pressed.
877 * You can get the last state of the form and possibly save it for this user by using
878 * value 'mform_showadvanced_last' in submitted data.
880 * @param boolean $showadvancedNow
882 function setShowAdvanced($showadvancedNow = null){
883 if ($showadvancedNow === null){
884 if ($this->_showAdvanced
!== null){
886 } else { //if setShowAdvanced is called without any preference
887 //make the default to not show advanced elements.
888 $showadvancedNow = get_user_preferences(
889 moodle_strtolower($this->_formName
.'_showadvanced', 0));
892 //value of hidden element
893 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT
);
895 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW
);
896 //toggle if button pressed or else stay the same
897 if ($hiddenLast == -1) {
898 $next = $showadvancedNow;
899 } elseif ($buttonPressed) { //toggle on button press
900 $next = !$hiddenLast;
904 $this->_showAdvanced
= $next;
905 if ($showadvancedNow != $next){
906 set_user_preference($this->_formName
.'_showadvanced', $next);
908 $this->setConstants(array('mform_showadvanced_last'=>$next));
910 function getShowAdvanced(){
911 return $this->_showAdvanced
;
918 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
923 function accept(&$renderer) {
924 if (method_exists($renderer, 'setAdvancedElements')){
925 //check for visible fieldsets where all elements are advanced
926 //and mark these headers as advanced as well.
927 //And mark all elements in a advanced header as advanced
928 $stopFields = $renderer->getStopFieldSetElements();
930 $lastHeaderAdvanced = false;
931 $anyAdvanced = false;
932 foreach (array_keys($this->_elements
) as $elementIndex){
933 $element =& $this->_elements
[$elementIndex];
935 // if closing header and any contained element was advanced then mark it as advanced
936 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
937 if ($anyAdvanced && !is_null($lastHeader)){
938 $this->setAdvanced($lastHeader->getName());
940 $lastHeaderAdvanced = false;
943 } elseif ($lastHeaderAdvanced) {
944 $this->setAdvanced($element->getName());
947 if ($element->getType()=='header'){
948 $lastHeader =& $element;
949 $anyAdvanced = false;
950 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
951 } elseif (isset($this->_advancedElements
[$element->getName()])){
955 // the last header may not be closed yet...
956 if ($anyAdvanced && !is_null($lastHeader)){
957 $this->setAdvanced($lastHeader->getName());
959 $renderer->setAdvancedElements($this->_advancedElements
);
962 parent
::accept($renderer);
967 function closeHeaderBefore($elementName){
968 $renderer =& $this->defaultRenderer();
969 $renderer->addStopFieldsetElements($elementName);
973 * Should be used for all elements of a form except for select, radio and checkboxes which
974 * clean their own data.
976 * @param string $elementname
977 * @param integer $paramtype use the constants PARAM_*.
978 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
979 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
980 * It will strip all html tags. But will still let tags for multilang support
982 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
983 * html editor. Data from the editor is later cleaned before display using
984 * format_text() function. PARAM_RAW can also be used for data that is validated
985 * by some other way or printed by p() or s().
986 * * PARAM_INT should be used for integers.
987 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
990 function setType($elementname, $paramtype) {
991 $this->_types
[$elementname] = $paramtype;
995 * See description of setType above. This can be used to set several types at once.
997 * @param array $paramtypes
999 function setTypes($paramtypes) {
1000 $this->_types
= $paramtypes +
$this->_types
;
1003 function updateSubmission($submission, $files) {
1004 $this->_flagSubmitted
= false;
1006 if (empty($submission)) {
1007 $this->_submitValues
= array();
1009 foreach ($submission as $key=>$s) {
1010 if (array_key_exists($key, $this->_types
)) {
1011 $submission[$key] = clean_param($s, $this->_types
[$key]);
1014 $this->_submitValues
= $this->_recursiveFilter('stripslashes', $submission);
1015 $this->_flagSubmitted
= true;
1018 if (empty($files)) {
1019 $this->_submitFiles
= array();
1021 if (1 == get_magic_quotes_gpc()) {
1022 foreach (array_keys($files) as $elname) {
1023 // dangerous characters in filenames are cleaned later in upload_manager
1024 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
1027 $this->_submitFiles
= $files;
1028 $this->_flagSubmitted
= true;
1031 // need to tell all elements that they need to update their value attribute.
1032 foreach (array_keys($this->_elements
) as $key) {
1033 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
1037 function getReqHTML(){
1038 return $this->_reqHTML
;
1041 function getAdvancedHTML(){
1042 return $this->_advancedHTML
;
1046 * Initializes a default form value. Used to specify the default for a new entry where
1047 * no data is loaded in using moodleform::set_data()
1049 * @param string $elementname element name
1050 * @param mixed $values values for that element name
1051 * @param bool $slashed the default value is slashed
1055 function setDefault($elementName, $defaultValue, $slashed=false){
1056 $filter = $slashed ?
'stripslashes' : NULL;
1057 $this->setDefaults(array($elementName=>$defaultValue), $filter);
1058 } // end func setDefault
1060 * Add an array of buttons to the form
1061 * @param array $buttons An associative array representing help button to attach to
1062 * to the form. keys of array correspond to names of elements in form.
1066 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1068 foreach ($buttons as $elementname => $button){
1069 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1073 * Add a single button.
1075 * @param string $elementname name of the element to add the item to
1076 * @param array $button - arguments to pass to function $function
1077 * @param boolean $suppresscheck - whether to throw an error if the element
1079 * @param string $function - function to generate html from the arguments in $button
1081 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
1082 if (array_key_exists($elementname, $this->_elementIndex
)){
1083 //_elements has a numeric index, this code accesses the elements by name
1084 $element=&$this->_elements
[$this->_elementIndex
[$elementname]];
1085 if (method_exists($element, 'setHelpButton')){
1086 $element->setHelpButton($button, $function);
1089 $a->name
=$element->getName();
1090 $a->classname
=get_class($element);
1091 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
1093 }elseif (!$suppresscheck){
1094 print_error('nonexistentformelements', 'form', '', $elementname);
1099 * Set constant value not overriden by _POST or _GET
1100 * note: this does not work for complex names with [] :-(
1101 * @param string $elname name of element
1102 * @param mixed $value
1105 function setConstant($elname, $value) {
1106 $this->_constantValues
= HTML_QuickForm
::arrayMerge($this->_constantValues
, array($elname=>$value));
1107 $element =& $this->getElement($elname);
1108 $element->onQuickFormEvent('updateValue', null, $this);
1111 function exportValues($elementList= null, $addslashes=true){
1112 $unfiltered = array();
1113 if (null === $elementList) {
1114 // iterate over all elements, calling their exportValue() methods
1115 $emptyarray = array();
1116 foreach (array_keys($this->_elements
) as $key) {
1117 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
){
1118 $value = $this->_elements
[$key]->exportValue($emptyarray, true);
1120 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
1123 if (is_array($value)) {
1124 // This shit throws a bogus warning in PHP 4.3.x
1125 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
1129 if (!is_array($elementList)) {
1130 $elementList = array_map('trim', explode(',', $elementList));
1132 foreach ($elementList as $elementName) {
1133 $value = $this->exportValue($elementName);
1134 if (PEAR
::isError($value)) {
1137 $unfiltered[$elementName] = $value;
1142 return $this->_recursiveFilter('addslashes', $unfiltered);
1148 * Adds a validation rule for the given field
1150 * If the element is in fact a group, it will be considered as a whole.
1151 * To validate grouped elements as separated entities,
1152 * use addGroupRule instead of addRule.
1154 * @param string $element Form element name
1155 * @param string $message Message to display for invalid data
1156 * @param string $type Rule type, use getRegisteredRules() to get types
1157 * @param string $format (optional)Required for extra rule data
1158 * @param string $validation (optional)Where to perform validation: "server", "client"
1159 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1160 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1163 * @throws HTML_QuickForm_Error
1165 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1167 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
1168 if ($validation == 'client') {
1169 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1172 } // end func addRule
1174 * Adds a validation rule for the given group of elements
1176 * Only groups with a name can be assigned a validation rule
1177 * Use addGroupRule when you need to validate elements inside the group.
1178 * Use addRule if you need to validate the group as a whole. In this case,
1179 * the same rule will be applied to all elements in the group.
1180 * Use addRule if you need to validate the group against a function.
1182 * @param string $group Form group name
1183 * @param mixed $arg1 Array for multiple elements or error message string for one element
1184 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1185 * @param string $format (optional)Required for extra rule data
1186 * @param int $howmany (optional)How many valid elements should be in the group
1187 * @param string $validation (optional)Where to perform validation: "server", "client"
1188 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1191 * @throws HTML_QuickForm_Error
1193 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1195 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1196 if (is_array($arg1)) {
1197 foreach ($arg1 as $rules) {
1198 foreach ($rules as $rule) {
1199 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
1201 if ('client' == $validation) {
1202 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1206 } elseif (is_string($arg1)) {
1208 if ($validation == 'client') {
1209 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1212 } // end func addGroupRule
1216 * Returns the client side validation script
1218 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1219 * and slightly modified to run rules per-element
1220 * Needed to override this because of an error with client side validation of grouped elements.
1223 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1225 function getValidationScript()
1227 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1231 include_once('HTML/QuickForm/RuleRegistry.php');
1232 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1243 foreach ($this->_rules
as $elementName => $rules) {
1244 foreach ($rules as $rule) {
1245 if ('client' == $rule['validation']) {
1246 unset($element); //TODO: find out how to properly initialize it
1248 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1249 $rule['message'] = strtr($rule['message'], $js_escape);
1251 if (isset($rule['group'])) {
1252 $group =& $this->getElement($rule['group']);
1253 // No JavaScript validation for frozen elements
1254 if ($group->isFrozen()) {
1257 $elements =& $group->getElements();
1258 foreach (array_keys($elements) as $key) {
1259 if ($elementName == $group->getElementName($key)) {
1260 $element =& $elements[$key];
1264 } elseif ($dependent) {
1266 $element[] =& $this->getElement($elementName);
1267 foreach ($rule['dependent'] as $elName) {
1268 $element[] =& $this->getElement($elName);
1271 $element =& $this->getElement($elementName);
1273 // No JavaScript validation for frozen elements
1274 if (is_object($element) && $element->isFrozen()) {
1276 } elseif (is_array($element)) {
1277 foreach (array_keys($element) as $key) {
1278 if ($element[$key]->isFrozen()) {
1283 // Fix for bug displaying errors for elements in a group
1284 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1285 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1286 $test[$elementName][1]=$element;
1292 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1293 // the form, and then that form field gets corrupted by the code that follows.
1297 <script type="text/javascript">
1300 var skipClientValidation = false;
1302 function qf_errorHandler(element, _qfMsg) {
1303 div = element.parentNode;
1304 if (_qfMsg != \'\') {
1305 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1307 errorSpan = document.createElement("span");
1308 errorSpan.id = \'id_error_\'+element.name;
1309 errorSpan.className = "error";
1310 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1313 while (errorSpan.firstChild) {
1314 errorSpan.removeChild(errorSpan.firstChild);
1317 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1318 errorSpan.appendChild(document.createElement("br"));
1320 if (div.className.substr(div.className.length - 6, 6) != " error"
1321 && div.className != "error") {
1322 div.className += " error";
1327 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1329 errorSpan.parentNode.removeChild(errorSpan);
1332 if (div.className.substr(div.className.length - 6, 6) == " error") {
1333 div.className = div.className.substr(0, div.className.length - 6);
1334 } else if (div.className == "error") {
1342 foreach ($test as $elementName => $jsandelement) {
1343 // Fix for bug displaying errors for elements in a group
1345 list($jsArr,$element)=$jsandelement;
1348 function validate_' . $this->_formName
. '_' . $elementName . '(element) {
1350 var errFlag = new Array();
1353 var frm = element.parentNode;
1354 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1355 frm = frm.parentNode;
1357 ' . join("\n", $jsArr) . '
1358 return qf_errorHandler(element, _qfMsg);
1362 ret = validate_' . $this->_formName
. '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1363 if (!ret && !first_focus) {
1365 frm.elements[\''.$elementName.'\'].focus();
1369 // Fix for bug displaying errors for elements in a group
1371 //$element =& $this->getElement($elementName);
1373 $valFunc = 'validate_' . $this->_formName
. '_' . $elementName . '(this)';
1374 $onBlur = $element->getAttribute('onBlur');
1375 $onChange = $element->getAttribute('onChange');
1376 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1377 'onChange' => $onChange . $valFunc));
1379 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1381 function validate_' . $this->_formName
. '(frm) {
1382 if (skipClientValidation) {
1387 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1388 var first_focus = false;
1389 ' . $validateJS . ';
1395 } // end func getValidationScript
1396 function _setDefaultRuleMessages(){
1397 foreach ($this->_rules
as $field => $rulesarr){
1398 foreach ($rulesarr as $key => $rule){
1399 if ($rule['message']===null){
1401 $a->format
=$rule['format'];
1402 $str=get_string('err_'.$rule['type'], 'form', $a);
1403 if (strpos($str, '[[')!==0){
1404 $this->_rules
[$field][$key]['message']=$str;
1411 function getLockOptionEndScript(){
1413 $iname = $this->getAttribute('id').'items';
1414 $js = '<script type="text/javascript">'."\n";
1415 $js .= '//<![CDATA['."\n";
1416 $js .= "var $iname = Array();\n";
1418 foreach ($this->_dependencies
as $dependentOn => $conditions){
1419 $js .= "{$iname}['$dependentOn'] = Array();\n";
1420 foreach ($conditions as $condition=>$values) {
1421 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1422 foreach ($values as $value=>$dependents) {
1423 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1425 foreach ($dependents as $dependent) {
1426 $elements = $this->_getElNamesRecursive($dependent);
1427 if (empty($elements)) {
1428 // probably element inside of some group
1429 $elements = array($dependent);
1431 foreach($elements as $element) {
1432 if ($element == $dependentOn) {
1435 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1442 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
1444 $js .='</script>'."\n";
1448 function _getElNamesRecursive($element) {
1449 if (is_string($element)) {
1450 if (!$this->elementExists($element)) {
1453 $element = $this->getElement($element);
1456 if (is_a($element, 'HTML_QuickForm_group')) {
1457 $elsInGroup = $element->getElements();
1459 foreach ($elsInGroup as $elInGroup){
1460 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1461 // not sure if this would work - groups nested in groups
1462 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1464 $elNames[] = $element->getElementName($elInGroup->getName());
1468 } else if (is_a($element, 'HTML_QuickForm_header')) {
1471 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1474 } else if (method_exists($element, 'getPrivateName')) {
1475 return array($element->getPrivateName());
1478 $elNames = array($element->getName());
1485 * Adds a dependency for $elementName which will be disabled if $condition is met.
1486 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1487 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1488 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1489 * of the $dependentOn element is $condition (such as equal) to $value.
1491 * @param string $elementName the name of the element which will be disabled
1492 * @param string $dependentOn the name of the element whose state will be checked for
1494 * @param string $condition the condition to check
1495 * @param mixed $value used in conjunction with condition.
1497 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1498 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
1499 $this->_dependencies
[$dependentOn] = array();
1501 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
1502 $this->_dependencies
[$dependentOn][$condition] = array();
1504 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
1505 $this->_dependencies
[$dependentOn][$condition][$value] = array();
1507 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
1510 function registerNoSubmitButton($buttonname){
1511 $this->_noSubmitButtons
[]=$buttonname;
1514 function isNoSubmitButton($buttonname){
1515 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
1518 function _registerCancelButton($addfieldsname){
1519 $this->_cancelButtons
[]=$addfieldsname;
1522 * Displays elements without HTML input tags.
1523 * This method is different to freeze() in that it makes sure no hidden
1524 * elements are included in the form.
1525 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1527 * This function also removes all previously defined rules.
1529 * @param mixed $elementList array or string of element(s) to be frozen
1532 * @throws HTML_QuickForm_Error
1534 function hardFreeze($elementList=null)
1536 if (!isset($elementList)) {
1537 $this->_freezeAll
= true;
1538 $elementList = array();
1540 if (!is_array($elementList)) {
1541 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1543 $elementList = array_flip($elementList);
1546 foreach (array_keys($this->_elements
) as $key) {
1547 $name = $this->_elements
[$key]->getName();
1548 if ($this->_freezeAll ||
isset($elementList[$name])) {
1549 $this->_elements
[$key]->freeze();
1550 $this->_elements
[$key]->setPersistantFreeze(false);
1551 unset($elementList[$name]);
1554 $this->_rules
[$name] = array();
1555 // if field is required, remove the rule
1556 $unset = array_search($name, $this->_required
);
1557 if ($unset !== false) {
1558 unset($this->_required
[$unset]);
1563 if (!empty($elementList)) {
1564 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);
1569 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1571 * This function also removes all previously defined rules of elements it freezes.
1573 * @param array $elementList array or string of element(s) not to be frozen
1576 * @throws HTML_QuickForm_Error
1578 function hardFreezeAllVisibleExcept($elementList)
1580 $elementList = array_flip($elementList);
1581 foreach (array_keys($this->_elements
) as $key) {
1582 $name = $this->_elements
[$key]->getName();
1583 $type = $this->_elements
[$key]->getType();
1585 if ($type == 'hidden'){
1586 // leave hidden types as they are
1587 } elseif (!isset($elementList[$name])) {
1588 $this->_elements
[$key]->freeze();
1589 $this->_elements
[$key]->setPersistantFreeze(false);
1592 $this->_rules
[$name] = array();
1593 // if field is required, remove the rule
1594 $unset = array_search($name, $this->_required
);
1595 if ($unset !== false) {
1596 unset($this->_required
[$unset]);
1603 * Tells whether the form was already submitted
1605 * This is useful since the _submitFiles and _submitValues arrays
1606 * may be completely empty after the trackSubmit value is removed.
1611 function isSubmitted()
1613 return parent
::isSubmitted() && (!$this->isFrozen());
1619 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
1620 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
1622 * Stylesheet is part of standard theme and should be automatically included.
1624 * @author Jamie Pratt <me@jamiep.org>
1625 * @license gpl license
1627 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
1630 * Element template array
1634 var $_elementTemplates;
1636 * Template used when opening a hidden fieldset
1637 * (i.e. a fieldset that is opened when there is no header element)
1641 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
1643 * Header Template string
1647 var $_headerTemplate =
1648 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
1651 * Template used when opening a fieldset
1655 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1658 * Template used when closing a fieldset
1662 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
1665 * Required Note template string
1669 var $_requiredNoteTemplate =
1670 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
1672 var $_advancedElements = array();
1675 * Whether to display advanced elements (on page load)
1677 * @var integer 1 means show 0 means hide
1681 function MoodleQuickForm_Renderer(){
1682 // switch next two lines for ol li containers for form items.
1683 // $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>');
1684 $this->_elementTemplates
= array(
1685 '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>',
1687 '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>',
1689 '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>',
1693 parent
::HTML_QuickForm_Renderer_Tableless();
1696 function setAdvancedElements($elements){
1697 $this->_advancedElements
= $elements;
1701 * What to do when starting the form
1703 * @param MoodleQuickForm $form
1705 function startForm(&$form){
1706 $this->_reqHTML
= $form->getReqHTML();
1707 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
1708 $this->_advancedHTML
= $form->getAdvancedHTML();
1709 $this->_showAdvanced
= $form->getShowAdvanced();
1710 parent
::startForm($form);
1711 if ($form->isFrozen()){
1712 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
1714 $this->_hiddenHtml
.= $form->_pageparams
;
1720 function startGroup(&$group, $required, $error){
1721 if (method_exists($group, 'getElementTemplateType')){
1722 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
1724 $html = $this->_elementTemplates
['default'];
1727 if ($this->_showAdvanced
){
1728 $advclass = ' advanced';
1730 $advclass = ' advanced hide';
1732 if (isset($this->_advancedElements
[$group->getName()])){
1733 $html =str_replace(' {advanced}', $advclass, $html);
1734 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1736 $html =str_replace(' {advanced}', '', $html);
1737 $html =str_replace('{advancedimg}', '', $html);
1739 if (method_exists($group, 'getHelpButton')){
1740 $html =str_replace('{help}', $group->getHelpButton(), $html);
1742 $html =str_replace('{help}', '', $html);
1744 $html =str_replace('{name}', $group->getName(), $html);
1745 $html =str_replace('{type}', 'fgroup', $html);
1747 $this->_templates
[$group->getName()]=$html;
1748 // Fix for bug in tableless quickforms that didn't allow you to stop a
1749 // fieldset before a group of elements.
1750 // if the element name indicates the end of a fieldset, close the fieldset
1751 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
1752 && $this->_fieldsetsOpen
> 0
1754 $this->_html
.= $this->_closeFieldsetTemplate
;
1755 $this->_fieldsetsOpen
--;
1757 parent
::startGroup($group, $required, $error);
1760 function renderElement(&$element, $required, $error){
1761 //manipulate id of all elements before rendering
1762 if (!is_null($element->getAttribute('id'))) {
1763 $id = $element->getAttribute('id');
1765 $id = $element->getName();
1767 //strip qf_ prefix and replace '[' with '_' and strip ']'
1768 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1769 if (strpos($id, 'id_') !== 0){
1770 $element->updateAttributes(array('id'=>'id_'.$id));
1773 //adding stuff to place holders in template
1774 if (method_exists($element, 'getElementTemplateType')){
1775 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
1777 $html = $this->_elementTemplates
['default'];
1779 if ($this->_showAdvanced
){
1780 $advclass = ' advanced';
1782 $advclass = ' advanced hide';
1784 if (isset($this->_advancedElements
[$element->getName()])){
1785 $html =str_replace(' {advanced}', $advclass, $html);
1787 $html =str_replace(' {advanced}', '', $html);
1789 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
1790 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
1792 $html =str_replace('{advancedimg}', '', $html);
1794 $html =str_replace('{type}', 'f'.$element->getType(), $html);
1795 $html =str_replace('{name}', $element->getName(), $html);
1796 if (method_exists($element, 'getHelpButton')){
1797 $html = str_replace('{help}', $element->getHelpButton(), $html);
1799 $html = str_replace('{help}', '', $html);
1802 if (!isset($this->_templates
[$element->getName()])) {
1803 $this->_templates
[$element->getName()] = $html;
1806 parent
::renderElement($element, $required, $error);
1809 function finishForm(&$form){
1810 if ($form->isFrozen()){
1811 $this->_hiddenHtml
= '';
1813 parent
::finishForm($form);
1814 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
1815 // add a lockoptions script
1816 $this->_html
= $this->_html
. "\n" . $script;
1820 * Called when visiting a header element
1822 * @param object An HTML_QuickForm_header element being visited
1826 function renderHeader(&$header) {
1827 $name = $header->getName();
1829 $id = empty($name) ?
'' : ' id="' . $name . '"';
1830 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
1831 if (is_null($header->_text
)) {
1833 } elseif (!empty($name) && isset($this->_templates
[$name])) {
1834 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
1836 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
1839 if (isset($this->_advancedElements
[$name])){
1840 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
1842 $header_html =str_replace('{advancedimg}', '', $header_html);
1844 $elementName='mform_showadvanced';
1845 if ($this->_showAdvanced
==0){
1846 $buttonlabel = get_string('showadvanced', 'form');
1848 $buttonlabel = get_string('hideadvanced', 'form');
1851 if (isset($this->_advancedElements
[$name])){
1852 require_js(array('yui_yahoo', 'yui_event'));
1853 // this is tricky - the first submit button on form is "clicked" if user presses enter
1854 // we do not want to "submit" using advanced button if javascript active
1855 $button_nojs = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" />';
1857 $buttonlabel = addslashes_js($buttonlabel);
1858 $showtext = addslashes_js(get_string('showadvanced', 'form'));
1859 $hidetext = addslashes_js(get_string('hideadvanced', 'form'));
1860 $button = '<script id="' . $name . '_script" type="text/javascript">' . "
1861 showAdvancedInit('{$name}_script', '$elementName', '$buttonlabel', '$hidetext', '$showtext');
1862 " . '</script><noscript><div style="display:inline">'.$button_nojs.'</div></noscript>'; // the extra div should fix xhtml validation
1864 $header_html = str_replace('{button}', $button, $header_html);
1866 $header_html = str_replace('{button}', '', $header_html);
1869 if ($this->_fieldsetsOpen
> 0) {
1870 $this->_html
.= $this->_closeFieldsetTemplate
;
1871 $this->_fieldsetsOpen
--;
1874 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
1875 if ($this->_showAdvanced
){
1876 $advclass = ' class="advanced"';
1878 $advclass = ' class="advanced hide"';
1880 if (isset($this->_advancedElements
[$name])){
1881 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1883 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1885 $this->_html
.= $openFieldsetTemplate . $header_html;
1886 $this->_fieldsetsOpen++
;
1887 } // end func renderHeader
1889 function getStopFieldsetElements(){
1890 return $this->_stopFieldsetElements
;
1895 $GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
1897 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1898 MoodleQuickForm
::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1899 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1900 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1901 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
1902 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1903 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1904 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
1905 MoodleQuickForm
::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
1906 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1907 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1908 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1909 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1910 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
1911 MoodleQuickForm
::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
1912 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1913 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
1914 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1915 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
1916 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
1917 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
1918 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1919 MoodleQuickForm
::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
1920 MoodleQuickForm
::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
1921 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1922 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
1923 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
1924 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
1925 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
1926 MoodleQuickForm
::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');