New styles for admin pages
[moodle.git] / lib / formslib.php
CommitLineData
2ae22002 1<?php // $Id$
da6f8763 2/**
3 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
da1320da 4 *
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
8 * and validation.
9 *
10 * See examples of use of this library in course/edit.php and course/edit_form.php
11 *
12 * A few notes :
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.
17 *
18 *
da6f8763 19 * @author Jamie Pratt
20 * @version $Id$
21 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
22 */
23
24//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else.
25if (FALSE===strstr(ini_get('include_path'), $CFG->libdir.'/pear' )){
26 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
27}
28require_once 'HTML/QuickForm.php';
29require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
30require_once 'HTML/QuickForm/Renderer/Tableless.php';
31
49292f8c 32require_once $CFG->libdir.'/uploadlib.php';
33
19194f82 34define('FORM_ADVANCEDIMAGEURL', $CFG->wwwroot.'/lib/form/adv.gif');
35define('FORM_REQIMAGEURL', $CFG->wwwroot.'/lib/form/req.gif');
36
a23f0aaf 37/**
38 * Callback called when PEAR throws an error
39 *
40 * @param PEAR_Error $error
41 */
42function pear_handle_error($error){
43 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
44 echo '<br /> <strong>Backtrace </strong>:';
45 print_object($error->backtrace);
46}
47
864cc1de 48if ($CFG->debug >= DEBUG_ALL){
a23f0aaf 49 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
864cc1de 50}
51
f07b9627 52
05f5c40c 53/**
da1320da 54 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
55 * use this class you should write a class defintion which extends this class or a more specific
56 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
57 *
58 * You will write your own definition() method which performs the form set up.
05f5c40c 59 */
7f40a229 60class moodleform {
49292f8c 61 var $_formname; // form name
3c7656b4 62 /**
63 * quickform object definition
64 *
65 * @var MoodleQuickForm
66 */
67 var $_form;
68 /**
69 * globals workaround
70 *
71 * @var array
72 */
73 var $_customdata;
74 /**
75 * file upload manager
76 *
77 * @var upload_manager
78 */
79 var $_upload_manager; //
7f40a229 80
19110c57 81
ebd3c7ac 82
da1320da 83 /**
84 * The constructor function calls the abstract function definition() and it will then
85 * process and clean and attempt to validate incoming data.
86 *
87 * It will call your custom validate method to validate data and will also check any rules
88 * you have specified in definition using addRule
89 *
90 * The name of the form (id attribute of the form) is automatically generated depending on
91 * the name you gave the class extending moodleform. You should call your class something
92 * like
93 *
a23f0aaf 94 * @param string $action the action attribute for the form. If empty defaults to auto detect the
95 * current url.
da1320da 96 * @param array $customdata if your form defintion method needs access to data such as $course
97 * $cm, etc. to construct the form definition then pass it in this array. You can
98 * use globals for somethings.
99 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
100 * be merged and used as incoming data to the form.
101 * @param string $target target frame for form submission. You will rarely use this. Don't use
102 * it if you don't need to as the target attribute is deprecated in xhtml
103 * strict.
104 * @param mixed $attributes you can pass a string of html attributes here or an array.
105 * @return moodleform
106 */
a23f0aaf 107 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null) {
108 if (empty($action)){
109 $action = strip_querystring(qualified_me());
110 }
f07b9627 111
72f46d11 112 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
7f40a229 113 $this->_customdata = $customdata;
5bc97c98 114 $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
feaf5d06 115 $this->set_upload_manager(new upload_manager());
7f40a229 116
117 $this->definition();
118
119 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
120 $this->_form->setDefault('sesskey', sesskey());
5bc97c98 121 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
122 $this->_form->setDefault('_qf__'.$this->_formname, 1);
123 $this->_form->_setDefaultRuleMessages();
7f40a229 124
125 // we have to know all input types before processing submission ;-)
126 $this->_process_submission($method);
127
05f5c40c 128 // update form definition based on final data
129 $this->definition_after_data();
7f40a229 130 }
05f5c40c 131
2c412890 132 /**
da1320da 133 * To autofocus on first form element or first element with error.
2c412890 134 *
135 * @return string javascript to select form element with first error or
da1320da 136 * first element if no errors. Use this as a parameter
137 * when calling print_header
2c412890 138 */
139 function focus(){
9403060a 140 $form =& $this->_form;
5c52df67 141 $elkeys=array_keys($form->_elementIndex);
9403060a 142 if (isset($form->_errors) && 0 != count($form->_errors)){
143 $errorkeys = array_keys($form->_errors);
144 $elkeys = array_intersect($elkeys, $errorkeys);
2c412890 145 }
9403060a 146 $names=null;
147 while (!$names){
148 $el = array_shift($elkeys);
149 $names=$form->_getElNamesRecursive($el);
150 }
151 $name=array_shift($names);
152 $focus='forms[\''.$this->_form->getAttribute('id').'\'].elements[\''.$name.'\']';
153 return $focus;
154 }
7f40a229 155
05f5c40c 156 /**
157 * Internal method. Alters submitted data to be suitable for quickforms processing.
158 * Must be called when the form is fully set up.
159 */
7f40a229 160 function _process_submission($method) {
161 $submission = array();
162 if ($method == 'post') {
163 if (!empty($_POST)) {
164 $submission = $_POST;
165 }
166 } else {
167 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
168 }
169
170 // following trick is needed to enable proper sesskey checks when using GET forms
5bc97c98 171 // the _qf__.$this->_formname serves as a marker that form was actually submitted
172 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
7f40a229 173 if (!confirm_sesskey()) {
174 error('Incorrect sesskey submitted, form not accepted!');
175 }
05f5c40c 176 $files = $_FILES;
7f40a229 177 } else {
178 $submission = array();
05f5c40c 179 $files = array();
7f40a229 180 }
181
05f5c40c 182 $this->_form->updateSubmission($submission, $files);
7f40a229 183 }
184
05f5c40c 185 /**
186 * Internal method. Validates all uploaded files.
187 */
49292f8c 188 function _validate_files() {
189 if (empty($_FILES)) {
190 // we do not need to do any checks because no files were submitted
191 // TODO: find out why server side required rule does not work for uploaded files;
192 // testing is easily done by always returning true from this function and adding
193 // $mform->addRule('soubor', get_string('required'), 'required', null, 'server');
194 // and submitting form without selected file
195 return true;
196 }
197 $errors = array();
198 $mform =& $this->_form;
199
49292f8c 200 // check the files
201 $status = $this->_upload_manager->preprocess_files();
202
203 // now check that we really want each file
204 foreach ($_FILES as $elname=>$file) {
205 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
206 $required = $mform->isElementRequired($elname);
207 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
208 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
209 // file not uploaded and not required - ignore it
210 continue;
211 }
212 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
213 }
214 } else {
feaf5d06 215 error('Incorrect upload attempt!');
49292f8c 216 }
217 }
218
219 // return errors if found
220 if ($status and 0 == count($errors)){
221 return true;
222 } else {
223 return $errors;
224 }
225 }
226
05f5c40c 227 /**
da1320da 228 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
229 * form definition (new entry form); this function is used to load in data where values
230 * already exist and data is being edited (edit entry form).
05f5c40c 231 *
232 * @param mixed $default_values object or array of default values
233 * @param bool $slased true if magic quotes applied to data values
234 */
7f40a229 235 function set_defaults($default_values, $slashed=false) {
236 if (is_object($default_values)) {
237 $default_values = (array)$default_values;
238 }
239 $filter = $slashed ? 'stripslashes' : NULL;
240 $this->_form->setDefaults($default_values, $filter);
38f394b2 241 //update form definition when data changed
05f5c40c 242 $this->definition_after_data();
7f40a229 243 }
244
c80a13c7 245 /**
feaf5d06 246 * Set custom upload manager.
c80a13c7 247 * Must be used BEFORE creating of file element!
248 *
feaf5d06 249 * @param object $um - custom upload manager
c80a13c7 250 */
feaf5d06 251 function set_upload_manager($um=false) {
252 if ($um === false) {
253 $um = new upload_manager();
c80a13c7 254 }
feaf5d06 255 $this->_upload_manager = $um;
c80a13c7 256
feaf5d06 257 $this->_form->setMaxFileSize($um->config->maxbytes);
c80a13c7 258 }
259
05f5c40c 260 /**
261 * Check that form was submitted. Does not check validity of submitted data.
262 *
263 * @return bool true if form properly submitted
264 */
7f40a229 265 function is_submitted() {
266 return $this->_form->isSubmitted();
267 }
268
a23f0aaf 269 function no_submit_button_pressed(){
270 static $nosubmit = null; // one check is enough
271 if (!is_null($nosubmit)){
272 return $nosubmit;
273 }
274 $mform =& $this->_form;
275 $nosubmit = false;
f07b9627 276 if (!$this->is_submitted()){
277 return false;
278 }
a23f0aaf 279 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
280 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
281 $nosubmit = true;
282 break;
283 }
284 }
285 return $nosubmit;
286 }
287
288
05f5c40c 289 /**
290 * Check that form data is valid.
291 *
292 * @return bool true if form data valid
293 */
7f40a229 294 function is_validated() {
49292f8c 295 static $validated = null; // one validation is enough
3ba2c187 296 $mform =& $this->_form;
f07b9627 297
7f40a229 298 if ($validated === null) {
3ba2c187 299 $internal_val = $mform->validate();
300 $moodle_val = $this->validation($mform->exportValues(null, true));
7f40a229 301 if ($moodle_val !== true) {
a23f0aaf 302 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
7f40a229 303 foreach ($moodle_val as $element=>$msg) {
3ba2c187 304 $mform->setElementError($element, $msg);
7f40a229 305 }
a23f0aaf 306 $moodle_val = false;
307 } else {
308 $moodle_val = true;
7f40a229 309 }
7f40a229 310 }
49292f8c 311 $file_val = $this->_validate_files();
312 if ($file_val !== true) {
313 if (!empty($file_val)) {
314 foreach ($file_val as $element=>$msg) {
3ba2c187 315 $mform->setElementError($element, $msg);
49292f8c 316 }
317 }
318 $file_val = false;
319 }
320 $validated = ($internal_val and $moodle_val and $file_val);
7f40a229 321 }
f07b9627 322 if ($this->no_submit_button_pressed()){
323 return false;
324 } else {
325 return $validated;
326 }
7f40a229 327 }
328
19110c57 329 /**
330 * Return true if a cancel button has been pressed resulting in the form being submitted.
331 *
332 * @return boolean true if a cancel button has been pressed
333 */
334 function is_cancelled(){
335 $mform =& $this->_form;
a23f0aaf 336 if ($mform->isSubmitted()){
337 foreach ($mform->_cancelButtons as $cancelbutton){
338 if (optional_param($cancelbutton, 0, PARAM_RAW)){
339 return true;
340 }
19110c57 341 }
342 }
343 return false;
344 }
345
05f5c40c 346 /**
da1320da 347 * Return submitted data if properly submitted or returns NULL if validation fails or
348 * if there is no submitted data.
05f5c40c 349 *
350 * @param bool $slashed true means return data with addslashes applied
351 * @return object submitted data; NULL if not valid or not submitted
352 */
7f40a229 353 function data_submitted($slashed=true) {
19110c57 354 $mform =& $this->_form;
3ba2c187 355
7f40a229 356 if ($this->is_submitted() and $this->is_validated()) {
19110c57 357 $data = $mform->exportValues(null, $slashed);
5bc97c98 358 unset($data['sesskey']); // we do not need to return sesskey
359 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
7f40a229 360 if (empty($data)) {
361 return NULL;
362 } else {
363 return (object)$data;
364 }
365 } else {
366 return NULL;
367 }
368 }
369
05f5c40c 370 /**
371 * Save verified uploaded files into directory. Upload process can be customised from definition()
38f394b2 372 * method by creating instance of upload manager and storing it in $this->_upload_form
05f5c40c 373 *
374 * @param string $destination where to store uploaded files
375 * @return bool success
376 */
49292f8c 377 function save_files($destination) {
49292f8c 378 if ($this->is_submitted() and $this->is_validated()) {
379 return $this->_upload_manager->save_files($destination);
380 }
381 return false;
382 }
2b63df96 383
feaf5d06 384 /**
385 * If we're only handling one file (if inputname was given in the constructor)
386 * this will return the (possibly changed) filename of the file.
387 * @return mixed false in case of failure, string if ok
388 */
389 function get_new_filename() {
390 return $this->_upload_manager->get_new_filename();
391 }
392
05f5c40c 393 /**
394 * Print html form.
395 */
7f40a229 396 function display() {
397 $this->_form->display();
398 }
399
49292f8c 400 /**
05f5c40c 401 * Abstract method - always override!
49292f8c 402 *
403 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
404 */
7f40a229 405 function definition() {
406 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
407 }
2c412890 408
c08ac016 409 /**
05f5c40c 410 * Dummy stub method - override if you need to setup the form depending on current
411 * values. This method is called after definition(), data submission and set_defaults().
412 * All form setup that is dependent on form values should go in here.
c08ac016 413 */
414 function definition_after_data(){
c08ac016 415 }
7f40a229 416
05f5c40c 417 /**
418 * Dummy stub method - override if you needed to perform some extra validation.
419 * If there are errors return array of errors ("fieldname"=>"error message"),
420 * otherwise true if ok.
38f394b2 421 *
05f5c40c 422 * @param array $data array of ("fieldname"=>value) of submitted data
38f394b2 423 * @return bool array of errors or true if ok
05f5c40c 424 */
7f40a229 425 function validation($data) {
7f40a229 426 return true;
427 }
ebd3c7ac 428
19110c57 429
ebd3c7ac 430
19194f82 431
a23f0aaf 432
616b549a 433 /**
434 * Method to add a repeating group of elements to a form.
435 *
436 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
437 * @param integer $repeats no of times to repeat elements initially
438 * @param array $options Array of options to apply to elements. Array keys are element names.
439 * This is an array of arrays. The second sets of keys are the option types
440 * for the elements :
441 * 'default' - default value is value
442 * 'type' - PARAM_* constant is value
443 * 'helpbutton' - helpbutton params array is value
444 * 'disabledif' - last three moodleform::disabledIf()
445 * params are value as an array
446 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
447 * @param string $addfieldsname name for button to add more fields
448 * @param int $addfieldsno how many fields to add at a time
271ffe3f 449 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
a23f0aaf 450 * @return int no of repeats of element in this page
616b549a 451 */
271ffe3f 452 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, $addfieldsname, $addfieldsno=5, $addstring=null){
453 if ($addstring===null){
454 $addstring = get_string('addfields', 'form', $addfieldsno);
455 } else {
456 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
457 }
ebd3c7ac 458 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
459 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
460 if (!empty($addfields)){
461 $repeats += $addfieldsno;
462 }
ebd3c7ac 463 $mform =& $this->_form;
a23f0aaf 464 $mform->registerNoSubmitButton($addfieldsname);
ebd3c7ac 465 $mform->addElement('hidden', $repeathiddenname, $repeats);
466 //value not to be overridden by submitted value
467 $mform->setConstants(array($repeathiddenname=>$repeats));
468 for ($i=0; $i<$repeats; $i++) {
469 foreach ($elementobjs as $elementobj){
271ffe3f 470 $elementclone = clone($elementobj);
ebd3c7ac 471 $name=$elementclone->getName();
86aab05c 472 if (!empty($name)){
473 $elementclone->setName($name."[$i]");
474 }
ebd3c7ac 475 if (is_a($elementclone, 'HTML_QuickForm_header')){
476 $value=$elementclone->_text;
271ffe3f 477 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
478
479 } else {
480 $value=$elementclone->getLabel();
481 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
ebd3c7ac 482
483 }
484 $mform->addElement($elementclone);
485 }
486 }
487 for ($i=0; $i<$repeats; $i++) {
488 foreach ($options as $elementname => $elementoptions){
489 $pos=strpos($elementname, '[');
490 if ($pos!==FALSE){
491 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
492 $realelementname .= substr($elementname, $pos+1);
493 }else {
494 $realelementname = $elementname."[$i]";
495 }
496 foreach ($elementoptions as $option => $params){
497
498 switch ($option){
499 case 'default' :
500 $mform->setDefault($realelementname, $params);
501 break;
502 case 'type' :
503 $mform->setType($realelementname, $params);
504 break;
505 case 'helpbutton' :
506 $mform->setHelpButton($realelementname, $params);
507 break;
508 case 'disabledif' :
509 $mform->disabledIf($realelementname, $params[0], $params[1], $params[2]);
510 break;
511
512 }
513 }
514 }
515 }
271ffe3f 516 $mform->addElement('submit', $addfieldsname, $addstring);
a23f0aaf 517
518 $mform->closeHeaderBefore($addfieldsname);
ebd3c7ac 519
19194f82 520 return $repeats;
ebd3c7ac 521 }
a23f0aaf 522 /**
1d284fbd 523 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
a23f0aaf 524 * if you don't want a cancel button in your form. If you have a cancel button make sure you
525 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
526 * get data with data_submitted().
527 *
528 * @param boolean $cancel whether to show cancel button, default true
529 * @param boolean $revert whether to show revert button, default true
530 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
531 */
1d284fbd 532 function add_action_buttons($cancel = true, $submitlabel=null){
a23f0aaf 533 if (is_null($submitlabel)){
534 $submitlabel = get_string('savechanges');
535 }
536 $mform =& $this->_form;
1d284fbd 537 if ($cancel){
538 //when two elements we need a group
a23f0aaf 539 $buttonarray=array();
540 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1d284fbd 541 $buttonarray[] = &$mform->createElement('cancel');
a23f0aaf 542 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
543 $mform->closeHeaderBefore('buttonar');
544 } else {
545 //no group needed
546 $mform->addElement('submit', 'submitbutton', $submitlabel);
547 $mform->closeHeaderBefore('submitbutton');
548 }
549 }
7f40a229 550}
551
da1320da 552/**
553 * You never extend this class directly. The class methods of this class are available from
554 * the private $this->_form property on moodleform and it's children. You generally only
555 * call methods on this class from within abstract methods that you override on moodleform such
556 * as definition and definition_after_data
557 *
558 */
7f40a229 559class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
560 var $_types = array();
50ef8eb9 561 var $_dependencies = array();
19110c57 562 /**
563 * Array of buttons that if pressed do not result in the processing of the form.
564 *
565 * @var array
566 */
567 var $_noSubmitButtons=array();
568 /**
569 * Array of buttons that if pressed do not result in the processing of the form.
570 *
571 * @var array
572 */
573 var $_cancelButtons=array();
7f40a229 574
19194f82 575 /**
576 * Array whose keys are element names. If the key exists this is a advanced element
577 *
578 * @var array
579 */
580 var $_advancedElements = array();
581
582 /**
583 * Whether to display advanced elements (on page load)
584 *
585 * @var boolean
586 */
587 var $_showAdvanced = null;
588
f07b9627 589 /**
590 * The form name is derrived from the class name of the wrapper minus the trailing form
591 * It is a name with words joined by underscores whereas the id attribute is words joined by
592 * underscores.
593 *
594 * @var unknown_type
595 */
596 var $_formName = '';
597
da6f8763 598 /**
599 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
600 * @param string $formName Form's name.
601 * @param string $method (optional)Form's method defaults to 'POST'
602 * @param string $action (optional)Form's action
603 * @param string $target (optional)Form's target defaults to none
604 * @param mixed $attributes (optional)Extra attributes for <form> tag
605 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
606 * @access public
607 */
7f40a229 608 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
da6f8763 609 global $CFG;
271ffe3f 610 static $formcounter = 1;
7f40a229 611
da6f8763 612 HTML_Common::HTML_Common($attributes);
da6f8763 613 $target = empty($target) ? array() : array('target' => $target);
f07b9627 614 $this->_formName = $formName;
da6f8763 615 //no 'name' atttribute for form in xhtml strict :
271ffe3f 616 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
617 $formcounter++;
da6f8763 618 $this->updateAttributes($attributes);
da6f8763 619
7f40a229 620 //this is custom stuff for Moodle :
da6f8763 621 $oldclass= $this->getAttribute('class');
622 if (!empty($oldclass)){
623 $this->updateAttributes(array('class'=>$oldclass.' mform'));
624 }else {
80f962df 625 $this->updateAttributes(array('class'=>'mform'));
da6f8763 626 }
19194f82 627 $this->_reqHTML = '<img alt="'.get_string('requiredelement', 'form').'" src="'.FORM_REQIMAGEURL.'" />';
628 $this->_advancedHTML = '<img alt="'.get_string('advancedelement', 'form').'" src="'.FORM_ADVANCEDIMAGEURL.'" />';
3d685169 629 $this->setRequiredNote(get_string('denotesreq', 'form',
da6f8763 630 helpbutton('requiredelement', get_string('requiredelement', 'form'),'moodle',
3ba2c187 631 true, false, '', true, '<img alt="'.get_string('requiredelement', 'form').'" src="'.
19194f82 632 FORM_REQIMAGEURL.'" />')));
633 }
634
a23f0aaf 635 /**
636 * Use this method to indicate an element in a form is an advanced field. If items in a form
637 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
638 * form so the user can decide whether to display advanced form controls.
639 *
640 * If you set a header element to advanced then all elements it contains will also be set as advanced.
641 *
642 * @param string $elementName group or element name (not the element name of something inside a group).
643 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
644 */
645 function setAdvanced($elementName, $advanced=true){
646 if ($advanced){
647 $this->_advancedElements[$elementName]='';
648 } elseif (isset($this->_advancedElements[$elementName])) {
649 unset($this->_advancedElements[$elementName]);
650 }
651 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
652 $this->setShowAdvanced();
653 $this->registerNoSubmitButton('mform_showadvanced');
654
655 $this->addElement('hidden', 'mform_showadvanced_last');
656 }
657 }
658 /**
659 * Set whether to show advanced elements in the form on first displaying form. Default is not to
660 * display advanced elements in the form until 'Show Advanced' is pressed.
661 *
662 * You can get the last state of the form and possibly save it for this user by using
663 * value 'mform_showadvanced_last' in submitted data.
664 *
665 * @param boolean $showadvancedNow
666 */
667 function setShowAdvanced($showadvancedNow = null){
668 if ($showadvancedNow === null){
669 if ($this->_showAdvanced !== null){
670 return;
671 } else { //if setShowAdvanced is called without any preference
672 //make the default to not show advanced elements.
f07b9627 673 $showadvancedNow = get_user_preferences(
674 moodle_strtolower($this->_formName.'_showadvanced', 0));
a23f0aaf 675 }
a23f0aaf 676 }
677 //value of hidden element
678 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
679 //value of button
680 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
681 //toggle if button pressed or else stay the same
682 if ($hiddenLast == -1) {
683 $next = $showadvancedNow;
684 } elseif ($buttonPressed) { //toggle on button press
685 $next = !$hiddenLast;
686 } else {
687 $next = $hiddenLast;
688 }
689 $this->_showAdvanced = $next;
f07b9627 690 if ($showadvancedNow != $next){
691 set_user_preference($this->_formName.'_showadvanced', $next);
692 }
a23f0aaf 693 $this->setConstants(array('mform_showadvanced_last'=>$next));
19194f82 694 }
695 function getShowAdvanced(){
696 return $this->_showAdvanced;
697 }
698
19194f82 699
700 /**
701 * Accepts a renderer
702 *
703 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
704 * @since 3.0
705 * @access public
706 * @return void
707 */
708 function accept(&$renderer)
709 {
710 if (method_exists($renderer, 'setAdvancedElements')){
711 //check for visible fieldsets where all elements are advanced
712 //and mark these headers as advanced as well.
713 //And mark all elements in a advanced header as advanced
714 $stopFields = $renderer->getStopFieldSetElements();
715 $lastHeader = null;
716 $lastHeaderAdvanced = false;
717 $anyAdvanced = false;
718 foreach (array_keys($this->_elements) as $elementIndex){
719 $element =& $this->_elements[$elementIndex];
720 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
721 if ($anyAdvanced && ($lastHeader!==null)){
722 $this->setAdvanced($lastHeader->getName());
723 }
724 $lastHeaderAdvanced = false;
725 } elseif ($lastHeaderAdvanced) {
726 $this->setAdvanced($element->getName());
727 }
728 if ($element->getType()=='header'){
729 $lastHeader =& $element;
730 $anyAdvanced = false;
731 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
732 } elseif (isset($this->_advancedElements[$element->getName()])){
733 $anyAdvanced = true;
734 }
735 }
736 $renderer->setAdvancedElements($this->_advancedElements);
737 if (count($this->_advancedElements)){
738
739 }
740 }
741 parent::accept($renderer);
742 }
743
19194f82 744
19194f82 745
746 function closeHeaderBefore($elementName){
747 $renderer =& $this->defaultRenderer();
748 $renderer->addStopFieldsetElements($elementName);
da6f8763 749 }
bb40325e 750
da1320da 751 /**
752 * Should be used for all elements of a form except for select, radio and checkboxes which
753 * clean their own data.
754 *
755 * @param string $elementname
756 * @param integer $paramtype use the constants PARAM_*.
757 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
758 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
759 * It will strip all html tags. But will still let tags for multilang support
760 * through.
761 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
762 * html editor. Data from the editor is later cleaned before display using
763 * format_text() function. PARAM_RAW can also be used for data that is validated
764 * by some other way or printed by p() or s().
765 * * PARAM_INT should be used for integers.
766 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
767 * form actions.
768 */
7f40a229 769 function setType($elementname, $paramtype) {
770 $this->_types[$elementname] = $paramtype;
771 }
49292f8c 772
da1320da 773 /**
774 * See description of setType above. This can be used to set several types at once.
775 *
776 * @param array $paramtypes
777 */
c56f1826 778 function setTypes($paramtypes) {
779 $this->_types = $paramtypes + $this->_types;
780 }
49292f8c 781
782 function updateSubmission($submission, $files) {
783 $this->_flagSubmitted = false;
784
7f40a229 785 if (empty($submission)) {
786 $this->_submitValues = array();
7f40a229 787 } else {
788 foreach ($submission as $key=>$s) {
789 if (array_key_exists($key, $this->_types)) {
790 $submission[$key] = clean_param($s, $this->_types[$key]);
791 }
792 }
793 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
794 $this->_flagSubmitted = true;
795 }
796
49292f8c 797 if (empty($files)) {
798 $this->_submitFiles = array();
799 } else {
800 if (1 == get_magic_quotes_gpc()) {
801 foreach ($files as $elname=>$file) {
802 // dangerous characters in filenames are cleaned later in upload_manager
803 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
804 }
805 }
806 $this->_submitFiles = $files;
807 $this->_flagSubmitted = true;
808 }
809
2c412890 810 // need to tell all elements that they need to update their value attribute.
811 foreach (array_keys($this->_elements) as $key) {
812 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
813 }
7f40a229 814 }
815
da6f8763 816 function getReqHTML(){
817 return $this->_reqHTML;
818 }
7f40a229 819
19194f82 820 function getAdvancedHTML(){
821 return $this->_advancedHTML;
822 }
823
7f40a229 824 /**
da1320da 825 * Initializes a default form value. Used to specify the default for a new entry where
826 * no data is loaded in using moodleform::set_defaults()
7f40a229 827 *
828 * @param string $elementname element name
829 * @param mixed $values values for that element name
830 * @param bool $slashed the default value is slashed
831 * @access public
832 * @return void
833 */
834 function setDefault($elementName, $defaultValue, $slashed=false){
835 $filter = $slashed ? 'stripslashes' : NULL;
836 $this->setDefaults(array($elementName=>$defaultValue), $filter);
837 } // end func setDefault
da6f8763 838 /**
c56f1826 839 * Add an array of buttons to the form
7f40a229 840 * @param array $buttons An associative array representing help button to attach to
da6f8763 841 * to the form. keys of array correspond to names of elements in form.
7f40a229 842 *
da6f8763 843 * @access public
844 */
d4fe14d3 845 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
7f40a229 846
c56f1826 847 foreach ($buttons as $elementname => $button){
d4fe14d3 848 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
da6f8763 849 }
850 }
c56f1826 851 /**
da1320da 852 * Add a single button.
c56f1826 853 *
854 * @param string $elementname name of the element to add the item to
d4fe14d3 855 * @param array $button - arguments to pass to function $function
c56f1826 856 * @param boolean $suppresscheck - whether to throw an error if the element
857 * doesn't exist.
d4fe14d3 858 * @param string $function - function to generate html from the arguments in $button
c56f1826 859 */
d4fe14d3 860 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
c56f1826 861 if (array_key_exists($elementname, $this->_elementIndex)){
862 //_elements has a numeric index, this code accesses the elements by name
863 $element=&$this->_elements[$this->_elementIndex[$elementname]];
864 if (method_exists($element, 'setHelpButton')){
d4fe14d3 865 $element->setHelpButton($button, $function);
c56f1826 866 }else{
867 $a=new object();
868 $a->name=$element->getName();
869 $a->classname=get_class($element);
870 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
871 }
872 }elseif (!$suppresscheck){
873 print_error('nonexistentformelements', 'form', '', $elementname);
2c412890 874 }
c56f1826 875 }
7f40a229 876
42f248e6 877 function exportValues($elementList= null, $addslashes=true){
da6f8763 878 $unfiltered=parent::exportValues($elementList);
7f40a229 879
da6f8763 880 if ($addslashes){
42f248e6 881 return $this->_recursiveFilter('addslashes',$unfiltered);
da6f8763 882 } else {
883 return $unfiltered;
884 }
885 }
f07b9627 886 /**
887 * Adds a validation rule for the given field
888 *
889 * If the element is in fact a group, it will be considered as a whole.
890 * To validate grouped elements as separated entities,
891 * use addGroupRule instead of addRule.
892 *
893 * @param string $element Form element name
894 * @param string $message Message to display for invalid data
895 * @param string $type Rule type, use getRegisteredRules() to get types
896 * @param string $format (optional)Required for extra rule data
897 * @param string $validation (optional)Where to perform validation: "server", "client"
898 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
899 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
900 * @since 1.0
901 * @access public
902 * @throws HTML_QuickForm_Error
903 */
904 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
905 {
906 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
907 if ($validation == 'client') {
908 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
909 }
910
911 } // end func addRule
912 /**
913 * Adds a validation rule for the given group of elements
914 *
915 * Only groups with a name can be assigned a validation rule
916 * Use addGroupRule when you need to validate elements inside the group.
917 * Use addRule if you need to validate the group as a whole. In this case,
918 * the same rule will be applied to all elements in the group.
919 * Use addRule if you need to validate the group against a function.
920 *
921 * @param string $group Form group name
922 * @param mixed $arg1 Array for multiple elements or error message string for one element
923 * @param string $type (optional)Rule type use getRegisteredRules() to get types
924 * @param string $format (optional)Required for extra rule data
925 * @param int $howmany (optional)How many valid elements should be in the group
926 * @param string $validation (optional)Where to perform validation: "server", "client"
927 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
928 * @since 2.5
929 * @access public
930 * @throws HTML_QuickForm_Error
931 */
932 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
933 {
934 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
935 if (is_array($arg1)) {
936 foreach ($arg1 as $elementIndex => $rules) {
937 foreach ($rules as $rule) {
938 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
939
940 if ('client' == $validation) {
941 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
942 }
943 }
944 }
945 } elseif (is_string($arg1)) {
946
947 if ($validation == 'client') {
948 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $formname . '; } catch(e) { return true; } return myValidator(this);'));
949 }
950 }
951 } // end func addGroupRule
952
953 // }}}
5bc97c98 954 /**
955 * Returns the client side validation script
956 *
957 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
958 * and slightly modified to run rules per-element
959 * Needed to override this because of an error with client side validation of grouped elements.
960 *
961 * @access public
962 * @return string Javascript to perform validation, empty string if no 'client' rules were added
963 */
964 function getValidationScript()
965 {
966 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
967 return '';
968 }
969
970 include_once('HTML/QuickForm/RuleRegistry.php');
971 $registry =& HTML_QuickForm_RuleRegistry::singleton();
972 $test = array();
973 $js_escape = array(
974 "\r" => '\r',
975 "\n" => '\n',
976 "\t" => '\t',
977 "'" => "\\'",
978 '"' => '\"',
979 '\\' => '\\\\'
980 );
981
982 foreach ($this->_rules as $elementName => $rules) {
983 foreach ($rules as $rule) {
984 if ('client' == $rule['validation']) {
da1320da 985 unset($element); //TODO: find out how to properly initialize it
5bc97c98 986
987 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
988 $rule['message'] = strtr($rule['message'], $js_escape);
989
990 if (isset($rule['group'])) {
991 $group =& $this->getElement($rule['group']);
992 // No JavaScript validation for frozen elements
993 if ($group->isFrozen()) {
994 continue 2;
995 }
996 $elements =& $group->getElements();
997 foreach (array_keys($elements) as $key) {
998 if ($elementName == $group->getElementName($key)) {
999 $element =& $elements[$key];
1000 break;
1001 }
1002 }
1003 } elseif ($dependent) {
1004 $element = array();
1005 $element[] =& $this->getElement($elementName);
1006 foreach ($rule['dependent'] as $idx => $elName) {
1007 $element[] =& $this->getElement($elName);
1008 }
1009 } else {
1010 $element =& $this->getElement($elementName);
1011 }
1012 // No JavaScript validation for frozen elements
1013 if (is_object($element) && $element->isFrozen()) {
1014 continue 2;
1015 } elseif (is_array($element)) {
1016 foreach (array_keys($element) as $key) {
1017 if ($element[$key]->isFrozen()) {
1018 continue 3;
1019 }
1020 }
1021 }
1022 // Fix for bug displaying errors for elements in a group
1023 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1024 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1025 $test[$elementName][1]=$element;
1026 //end of fix
1027 }
1028 }
1029 }
1030 $js = '
1031<script type="text/javascript">
1032//<![CDATA[
1cbb09f1 1033
1034var skipClientValidation = false;
1035
5bc97c98 1036function qf_errorHandler(element, _qfMsg) {
1037 div = element.parentNode;
1038 if (_qfMsg != \'\') {
e35c9eeb 1039 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1040 if (!errorSpan) {
1041 errorSpan = document.createElement("span");
e35c9eeb 1042 errorSpan.id = \'id_error_\'+element.name;
1043 errorSpan.className = "error";
fed13a5e 1044 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
5bc97c98 1045 }
fed13a5e 1046
e7004d05 1047 while (errorSpan.firstChild) {
1048 errorSpan.removeChild(errorSpan.firstChild);
5bc97c98 1049 }
2c412890 1050
e7004d05 1051 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
e35c9eeb 1052 errorSpan.appendChild(document.createElement("br"));
5bc97c98 1053
1054 if (div.className.substr(div.className.length - 6, 6) != " error"
1055 && div.className != "error") {
1056 div.className += " error";
1057 }
1058
1059 return false;
1060 } else {
e35c9eeb 1061 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1062 if (errorSpan) {
1063 errorSpan.parentNode.removeChild(errorSpan);
5bc97c98 1064 }
1065
1066 if (div.className.substr(div.className.length - 6, 6) == " error") {
1067 div.className = div.className.substr(0, div.className.length - 6);
1068 } else if (div.className == "error") {
1069 div.className = "";
1070 }
1071
1072 return true;
1073 }
1074}';
1075 $validateJS = '';
1076 foreach ($test as $elementName => $jsandelement) {
1077 // Fix for bug displaying errors for elements in a group
1078 //unset($element);
1079 list($jsArr,$element)=$jsandelement;
1080 //end of fix
1081 $js .= '
f07b9627 1082function validate_' . $this->_formName . '_' . $elementName . '(element) {
5bc97c98 1083 var value = \'\';
1084 var errFlag = new Array();
1085 var _qfGroups = {};
1086 var _qfMsg = \'\';
1087 var frm = element.parentNode;
1088 while (frm && frm.nodeName != "FORM") {
1089 frm = frm.parentNode;
1090 }
1091' . join("\n", $jsArr) . '
1092 return qf_errorHandler(element, _qfMsg);
1093}
1094';
1095 $validateJS .= '
f07b9627 1096 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;';
5bc97c98 1097 // Fix for bug displaying errors for elements in a group
1098 //unset($element);
1099 //$element =& $this->getElement($elementName);
1100 //end of fix
f07b9627 1101 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
5bc97c98 1102 $onBlur = $element->getAttribute('onBlur');
1103 $onChange = $element->getAttribute('onChange');
1104 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1105 'onChange' => $onChange . $valFunc));
1106 }
e7004d05 1107// do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
5bc97c98 1108 $js .= '
f07b9627 1109function validate_' . $this->_formName . '(frm) {
1cbb09f1 1110 if (skipClientValidation) {
1111 return true;
1112 }
5bc97c98 1113 var ret = true;
0befbdfd 1114
1115 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1116
5bc97c98 1117' . $validateJS . ';
1118 return ret;
1119}
1120//]]>
1121</script>';
1122 return $js;
1123 } // end func getValidationScript
1124 function _setDefaultRuleMessages(){
1125 foreach ($this->_rules as $field => $rulesarr){
1126 foreach ($rulesarr as $key => $rule){
1127 if ($rule['message']===null){
1128 $a=new object();
1129 $a->format=$rule['format'];
1130 $str=get_string('err_'.$rule['type'], 'form', $a);
1131 if (strpos($str, '[[')!==0){
1132 $this->_rules[$field][$key]['message']=$str;
2c412890 1133 }
5bc97c98 1134 }
1135 }
1136 }
1137 }
bb40325e 1138
d01a38cb 1139 function getLockOptionEndScript(){
f4ba7e1a 1140 $js = '<script type="text/javascript">'."\n";
5e87b920 1141 $js .= '//<![CDATA['."\n";
271ffe3f 1142 $js .= "var ".$this->getAttribute('id')."items= {";
50ef8eb9 1143 foreach ($this->_dependencies as $dependentOn => $elements){
46e648b6 1144 $js .= "'$dependentOn'".' : {dependents :[';
50ef8eb9 1145 foreach ($elements as $element){
11f260f4 1146 $elementNames = $this->_getElNamesRecursive($element['dependent']);
1147 foreach ($elementNames as $dependent){
1148 if ($dependent != $dependentOn) {
1149 $js.="'".$dependent."', ";
1150 }
1151 }
50ef8eb9 1152 }
1153 $js=rtrim($js, ', ');
1154 $js .= "],\n";
e24b7f85 1155 $js .= "condition : '{$element['condition']}',\n";
1156 $js .= "value : '{$element['value']}'},\n";
50ef8eb9 1157
1158 };
1159 $js=rtrim($js, ",\n");
1160 $js .= '};'."\n";
d01a38cb 1161 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
5e87b920 1162 $js .='//]]>'."\n";
50ef8eb9 1163 $js .='</script>'."\n";
1164 return $js;
bb40325e 1165 }
d01a38cb 1166
1167 function _getElNamesRecursive(&$element, $group=null){
1168 if ($group==null){
9403060a 1169 $el = $this->getElement($element);
d01a38cb 1170 } else {
9403060a 1171 $el = &$element;
d01a38cb 1172 }
1173 if (is_a($el, 'HTML_QuickForm_group')){
9403060a 1174 $group = $el;
1175 $elsInGroup = $group->getElements();
1176 $elNames = array();
d01a38cb 1177 foreach ($elsInGroup as $elInGroup){
1178 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1179 }
1180 }else{
9403060a 1181 if ($group != null){
1182 $elNames = array($group->getElementName($el->getName()));
1183 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1184 return null;
2dbd6409 1185 } elseif (method_exists($el, 'getPrivateName')) {
1186 return array($el->getPrivateName());
d01a38cb 1187 } else {
9403060a 1188 $elNames = array($el->getName());
d01a38cb 1189 }
1190 }
1191 return $elNames;
1192
50ef8eb9 1193 }
6e372b25 1194 /**
1195 * Adds a dependency for $elementName which will be disabled if $condition is met.
9403060a 1196 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1197 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
6e372b25 1198 * is checked. If $condition is something else then it is checked to see if the value
1199 * of the $dependentOn element is equal to $condition.
1200 *
1201 * @param string $elementName the name of the element which will be disabled
1202 * @param string $dependentOn the name of the element whose state will be checked for
1203 * condition
1204 * @param string $condition the condition to check
19110c57 1205 * @param mixed $value used in conjunction with condition.
6e372b25 1206 */
e24b7f85 1207 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value=null){
11f260f4 1208 $this->_dependencies[$dependentOn][] = array('dependent'=>$elementName,
e24b7f85 1209 'condition'=>$condition, 'value'=>$value);
bb40325e 1210 }
a23f0aaf 1211 function registerNoSubmitButton($buttonname){
1212 $this->_noSubmitButtons[]=$buttonname;
1213 }
1214 function isNoSubmitButton($buttonname){
1215 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
19110c57 1216 }
1217 function _registerCancelButton($addfieldsname){
1218 $this->_cancelButtons[]=$addfieldsname;
1219 }
da6f8763 1220}
1221
e24b7f85 1222
da6f8763 1223/**
7f40a229 1224 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
da6f8763 1225 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
7f40a229 1226 *
da6f8763 1227 * Stylesheet is part of standard theme and should be automatically included.
1228 *
1229 * @author Jamie Pratt <me@jamiep.org>
1230 * @license gpl license
1231 */
7f40a229 1232class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
da6f8763 1233
1234 /**
1235 * Element template array
1236 * @var array
1237 * @access private
1238 */
1239 var $_elementTemplates;
49c53687 1240 /**
1241 * Template used when opening a hidden fieldset
1242 * (i.e. a fieldset that is opened when there is no header element)
1243 * @var string
1244 * @access private
1245 */
1246 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\">";
19194f82 1247 /**
1248 * Header Template string
1249 * @var string
1250 * @access private
1251 */
1252 var $_headerTemplate =
a23f0aaf 1253 "\n\t\t<legend>{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div>\n\t\t";
7f40a229 1254
49c53687 1255 /**
1256 * Template used when closing a fieldset
1257 * @var string
1258 * @access private
1259 */
1260 var $_closeFieldsetTemplate = "\n\t\t</fieldset>";
42f248e6 1261
49c53687 1262 /**
1263 * Required Note template string
1264 * @var string
1265 * @access private
1266 */
7f40a229 1267 var $_requiredNoteTemplate =
49c53687 1268 "\n\t\t<div class=\"fdescription\">{requiredNote}</div>";
7f40a229 1269
19194f82 1270 var $_advancedElements = array();
1271
1272 /**
1273 * Whether to display advanced elements (on page load)
1274 *
1275 * @var integer 1 means show 0 means hide
1276 */
1277 var $_showAdvanced;
1278
7f40a229 1279 function MoodleQuickForm_Renderer(){
42f248e6 1280 // switch next two lines for ol li containers for form items.
49c53687 1281 // $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>");
b07b6c81 1282 $this->_elementTemplates = array('default'=>"\n\t\t<div class=\"fitem {advanced}<!-- BEGIN required --> required<!-- END required -->\"><span class=\"fitemtitle\"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg}</label>{help}</span><div class=\"felement {type}<!-- BEGIN error --> error<!-- END error -->\"><!-- BEGIN error --><span class=\"error\" id=\"id_error_{name}\">{error}</span><br /><!-- END error -->{element}</div></div>",
86aab05c 1283 'fieldset'=>"\n\t\t<div class=\"fitem {advanced}<!-- BEGIN required --> required<!-- END required -->\"><span class=\"fitemtitle\"><div class=\"fgrouplabel\">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg}</div>{help}</span><fieldset class=\"felement {type}<!-- BEGIN error --> error<!-- END error -->\"><!-- BEGIN error --><span class=\"error\" id=\"id_error_{name}\">{error}</span><br /><!-- END error -->{element}</fieldset></div>");
da6f8763 1284
1285 parent::HTML_QuickForm_Renderer_Tableless();
1286 }
7f40a229 1287
19194f82 1288 function setAdvancedElements($elements){
1289 $this->_advancedElements = $elements;
1290 }
1291
1292 /**
1293 * What to do when starting the form
1294 *
1295 * @param MoodleQuickForm $form
1296 */
da6f8763 1297 function startForm(&$form){
9403060a 1298 $this->_reqHTML = $form->getReqHTML();
1299 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
19194f82 1300 $this->_advancedHTML = $form->getAdvancedHTML();
1301 $this->_showAdvanced = $form->getShowAdvanced();
da6f8763 1302 parent::startForm($form);
1303 }
7f40a229 1304
da6f8763 1305 function startGroup(&$group, $required, $error){
1306 if (method_exists($group, 'getElementTemplateType')){
e249661f 1307 $html = $this->_elementTemplates[$group->getElementTemplateType()];
da6f8763 1308 }else{
1309 $html = $this->_elementTemplates['default'];
7f40a229 1310
da6f8763 1311 }
19194f82 1312 if ($this->_showAdvanced){
1313 $advclass = ' advanced';
1314 } else {
1315 $advclass = ' advanced hide';
1316 }
1317 if (isset($this->_advancedElements[$group->getName()])){
1318 $html =str_replace(' {advanced}', $advclass, $html);
1319 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1320 } else {
1321 $html =str_replace(' {advanced}', '', $html);
1322 $html =str_replace('{advancedimg}', '', $html);
1323 }
da6f8763 1324 if (method_exists($group, 'getHelpButton')){
1325 $html =str_replace('{help}', $group->getHelpButton(), $html);
1326 }else{
1327 $html =str_replace('{help}', '', $html);
da6f8763 1328 }
e7004d05 1329 $html =str_replace('{name}', $group->getName(), $html);
49c53687 1330 $html =str_replace('{type}', 'fgroup', $html);
7f40a229 1331
da6f8763 1332 $this->_templates[$group->getName()]=$html;
1333 // Fix for bug in tableless quickforms that didn't allow you to stop a
1334 // fieldset before a group of elements.
1335 // if the element name indicates the end of a fieldset, close the fieldset
1336 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1337 && $this->_fieldsetsOpen > 0
1338 ) {
1339 $this->_html .= $this->_closeFieldsetTemplate;
1340 $this->_fieldsetsOpen--;
1341 }
1342 parent::startGroup($group, $required, $error);
1343 }
7f40a229 1344
da6f8763 1345 function renderElement(&$element, $required, $error){
86aab05c 1346 //manipulate id of all elements before rendering
1347 if (!is_null($element->getAttribute('id'))) {
1348 $id = $element->getAttribute('id');
1349 } else {
1350 $id = $element->getName();
1351 }
1352 //strip qf_ prefix and replace '[' with '_' and strip ']'
1353 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1354 if (strpos($id, 'id_') !== 0){
1355 $element->updateAttributes(array('id'=>'id_'.$id));
1356 }
1357
1358 //adding stuff to place holders in template
da6f8763 1359 if (method_exists($element, 'getElementTemplateType')){
1360 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1361 }else{
1362 $html = $this->_elementTemplates['default'];
19194f82 1363 }
1364 if ($this->_showAdvanced){
1365 $advclass = ' advanced';
1366 } else {
1367 $advclass = ' advanced hide';
1368 }
1369 if (isset($this->_advancedElements[$element->getName()])){
1370 $html =str_replace(' {advanced}', $advclass, $html);
1371 } else {
1372 $html =str_replace(' {advanced}', '', $html);
1373 }
1374 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1375 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1376 } else {
1377 $html =str_replace('{advancedimg}', '', $html);
da6f8763 1378 }
49c53687 1379 $html =str_replace('{type}', 'f'.$element->getType(), $html);
e7004d05 1380 $html =str_replace('{name}', $element->getName(), $html);
da6f8763 1381 if (method_exists($element, 'getHelpButton')){
9403060a 1382 $html = str_replace('{help}', $element->getHelpButton(), $html);
da6f8763 1383 }else{
9403060a 1384 $html = str_replace('{help}', '', $html);
7f40a229 1385
da6f8763 1386 }
86aab05c 1387
9403060a 1388 $this->_templates[$element->getName()] = $html;
86aab05c 1389
da6f8763 1390 parent::renderElement($element, $required, $error);
1391 }
19194f82 1392
bb40325e 1393 function finishForm(&$form){
1394 parent::finishForm($form);
d01a38cb 1395 // add a lockoptions script
bb40325e 1396 if ('' != ($script = $form->getLockOptionEndScript())) {
1397 $this->_html = $this->_html . "\n" . $script;
1398 }
1399 }
19194f82 1400 /**
1401 * Called when visiting a header element
1402 *
1403 * @param object An HTML_QuickForm_header element being visited
1404 * @access public
1405 * @return void
1406 */
1407 function renderHeader(&$header) {
1408 $name = $header->getName();
1409
1410 $id = empty($name) ? '' : ' id="' . $name . '"';
1411 if (is_null($header->_text)) {
1412 $header_html = '';
1413 } elseif (!empty($name) && isset($this->_templates[$name])) {
1414 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1415 } else {
1416 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1417 }
1418
1419 if (isset($this->_advancedElements[$name])){
1420 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1421 } else {
1422 $header_html =str_replace('{advancedimg}', '', $header_html);
1423 }
1424 $elementName='mform_showadvanced';
1425 if ($this->_showAdvanced==0){
1426 $buttonlabel = get_string('showadvanced', 'form');
1427 } else {
1428 $buttonlabel = get_string('hideadvanced', 'form');
1429 }
1430
1431 if (isset($this->_advancedElements[$name])){
1432 $showtext="'".get_string('showadvanced', 'form')."'";
1433 $hidetext="'".get_string('hideadvanced', 'form')."'";
1434 //onclick returns false so if js is on then page is not submitted.
1435 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1436 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1437 $header_html =str_replace('{button}', $button, $header_html);
1438 } else {
1439 $header_html =str_replace('{button}', '', $header_html);
1440 }
1441
1442 if ($this->_fieldsetsOpen > 0) {
1443 $this->_html .= $this->_closeFieldsetTemplate;
1444 $this->_fieldsetsOpen--;
1445 }
1446
1447 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1448 if ($this->_showAdvanced){
1449 $advclass = ' class="advanced"';
1450 } else {
1451 $advclass = ' class="advanced hide"';
1452 }
1453 if (isset($this->_advancedElements[$name])){
1454 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1455 } else {
1456 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1457 }
1458 $this->_html .= $openFieldsetTemplate . $header_html;
1459 $this->_fieldsetsOpen++;
1460 } // end func renderHeader
1461
1462 function getStopFieldsetElements(){
1463 return $this->_stopFieldsetElements;
1464 }
da6f8763 1465}
1466
da6f8763 1467
9403060a 1468$GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
da6f8763 1469
7f40a229 1470MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1471MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1472MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1473MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1474MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1475MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1476MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1477MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1478MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1479MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1480MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
effa85f4 1481MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
7f40a229 1482MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1483MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
e2294b98 1484MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1485MoodleQuickForm::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
e0f40684 1486MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
d4fe14d3 1487MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
19110c57 1488MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3c7656b4 1489MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1490MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
a23f0aaf 1491MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1492MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
9e93222d 1493MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
111be766 1494MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
864cc1de 1495
2ae22002 1496?>