2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
25 * See examples of use of this library in course/edit.php and course/edit_form.php
28 * form definition is used for both printing of form and processing and should be the same
29 * for both or you may lose some submitted data which won't be let through.
30 * you should be using setType for every form element except select, radio or checkbox
31 * elements, these elements clean themselves.
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') ||
die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir
.'/filelib.php';
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
58 function pear_handle_error($error){
59 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60 echo '<br /> <strong>Backtrace </strong>:';
61 print_object($error->backtrace
);
64 if ($CFG->debugdeveloper
) {
65 //TODO: this is a wrong place to init PEAR!
66 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
67 $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
71 * Initalize javascript for date type form element
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
76 function form_init_date_js() {
81 $calendar = \core_calendar\type_factory
::get_calendar_instance();
82 if ($calendar->get_name() !== 'gregorian') {
83 // The YUI2 calendar only supports the gregorian calendar type.
86 $module = 'moodle-form-dateselector';
87 $function = 'M.form.dateselector.init_date_selectors';
88 $defaulttimezone = date_default_timezone_get();
90 $config = array(array(
91 'firstdayofweek' => $calendar->get_starting_weekday(),
92 'mon' => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
93 'tue' => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
94 'wed' => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
95 'thu' => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
96 'fri' => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
97 'sat' => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
98 'sun' => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
99 'january' => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
100 'february' => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
101 'march' => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
102 'april' => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
103 'may' => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
104 'june' => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
105 'july' => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
106 'august' => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
107 'september' => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
108 'october' => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
109 'november' => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
110 'december' => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
112 $PAGE->requires
->yui_module($module, $function, $config);
117 * Wrapper that separates quickforms syntax from moodle code
119 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
120 * use this class you should write a class definition which extends this class or a more specific
121 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
123 * You will write your own definition() method which performs the form set up.
126 * @copyright 2006 Jamie Pratt <me@jamiep.org>
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
128 * @todo MDL-19380 rethink the file scanning
130 abstract class moodleform
{
131 /** @var string name of the form */
132 protected $_formname; // form name
134 /** @var MoodleQuickForm quickform object definition */
137 /** @var array globals workaround */
138 protected $_customdata;
140 /** @var array submitted form data when using mforms with ajax */
141 protected $_ajaxformdata;
143 /** @var object definition_after_data executed flag */
144 protected $_definition_finalized = false;
146 /** @var bool|null stores the validation result of this form or null if not yet validated */
147 protected $_validated = null;
150 * The constructor function calls the abstract function definition() and it will then
151 * process and clean and attempt to validate incoming data.
153 * It will call your custom validate method to validate data and will also check any rules
154 * you have specified in definition using addRule
156 * The name of the form (id attribute of the form) is automatically generated depending on
157 * the name you gave the class extending moodleform. You should call your class something
160 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
161 * current url. If a moodle_url object then outputs params as hidden variables.
162 * @param mixed $customdata if your form defintion method needs access to data such as $course
163 * $cm, etc. to construct the form definition then pass it in this array. You can
164 * use globals for somethings.
165 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
166 * be merged and used as incoming data to the form.
167 * @param string $target target frame for form submission. You will rarely use this. Don't use
168 * it if you don't need to as the target attribute is deprecated in xhtml strict.
169 * @param mixed $attributes you can pass a string of html attributes here or an array.
170 * Special attribute 'data-random-ids' will randomise generated elements ids. This
171 * is necessary when there are several forms on the same page.
172 * Special attribute 'data-double-submit-protection' set to 'off' will turn off
173 * double-submit protection JavaScript - this may be necessary if your form sends
174 * downloadable files in response to a submit button, and can't call
175 * \core_form\util::form_download_complete();
176 * @param bool $editable
177 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
179 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
180 $ajaxformdata=null) {
181 global $CFG, $FULLME;
182 // no standard mform in moodle should allow autocomplete with the exception of user signup
183 if (empty($attributes)) {
184 $attributes = array('autocomplete'=>'off');
185 } else if (is_array($attributes)) {
186 $attributes['autocomplete'] = 'off';
188 if (strpos($attributes, 'autocomplete') === false) {
189 $attributes .= ' autocomplete="off" ';
195 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
196 $action = strip_querystring($FULLME);
197 if (!empty($CFG->sslproxy
)) {
198 // return only https links when using SSL proxy
199 $action = preg_replace('/^http:/', 'https:', $action, 1);
201 //TODO: use following instead of FULLME - see MDL-33015
202 //$action = strip_querystring(qualified_me());
204 // Assign custom data first, so that get_form_identifier can use it.
205 $this->_customdata
= $customdata;
206 $this->_formname
= $this->get_form_identifier();
207 $this->_ajaxformdata
= $ajaxformdata;
209 $this->_form
= new MoodleQuickForm($this->_formname
, $method, $action, $target, $attributes, $ajaxformdata);
211 $this->_form
->hardFreeze();
216 $this->_form
->addElement('hidden', 'sesskey', null); // automatic sesskey protection
217 $this->_form
->setType('sesskey', PARAM_RAW
);
218 $this->_form
->setDefault('sesskey', sesskey());
219 $this->_form
->addElement('hidden', '_qf__'.$this->_formname
, null); // form submission marker
220 $this->_form
->setType('_qf__'.$this->_formname
, PARAM_RAW
);
221 $this->_form
->setDefault('_qf__'.$this->_formname
, 1);
222 $this->_form
->_setDefaultRuleMessages();
224 // Hook to inject logic after the definition was provided.
225 $this->after_definition();
227 // we have to know all input types before processing submission ;-)
228 $this->_process_submission($method);
232 * Old syntax of class constructor. Deprecated in PHP7.
234 * @deprecated since Moodle 3.1
236 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
237 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
238 self
::__construct($action, $customdata, $method, $target, $attributes, $editable);
242 * It should returns unique identifier for the form.
243 * Currently it will return class name, but in case two same forms have to be
244 * rendered on same page then override function to get unique form identifier.
245 * e.g This is used on multiple self enrollments page.
247 * @return string form identifier.
249 protected function get_form_identifier() {
250 $class = get_class($this);
252 return preg_replace('/[^a-z0-9_]/i', '_', $class);
256 * To autofocus on first form element or first element with error.
258 * @param string $name if this is set then the focus is forced to a field with this name
259 * @return string javascript to select form element with first error or
260 * first element if no errors. Use this as a parameter
261 * when calling print_header
263 function focus($name=NULL) {
264 $form =& $this->_form
;
265 $elkeys = array_keys($form->_elementIndex
);
267 if (isset($form->_errors
) && 0 != count($form->_errors
)){
268 $errorkeys = array_keys($form->_errors
);
269 $elkeys = array_intersect($elkeys, $errorkeys);
273 if ($error or empty($name)) {
275 while (empty($names) and !empty($elkeys)) {
276 $el = array_shift($elkeys);
277 $names = $form->_getElNamesRecursive($el);
279 if (!empty($names)) {
280 $name = array_shift($names);
286 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
293 * Internal method. Alters submitted data to be suitable for quickforms processing.
294 * Must be called when the form is fully set up.
296 * @param string $method name of the method which alters submitted data
298 function _process_submission($method) {
299 $submission = array();
300 if (!empty($this->_ajaxformdata
)) {
301 $submission = $this->_ajaxformdata
;
302 } else if ($method == 'post') {
303 if (!empty($_POST)) {
304 $submission = $_POST;
308 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
311 // following trick is needed to enable proper sesskey checks when using GET forms
312 // the _qf__.$this->_formname serves as a marker that form was actually submitted
313 if (array_key_exists('_qf__'.$this->_formname
, $submission) and $submission['_qf__'.$this->_formname
] == 1) {
314 if (!confirm_sesskey()) {
315 print_error('invalidsesskey');
319 $submission = array();
322 $this->detectMissingSetType();
324 $this->_form
->updateSubmission($submission, $files);
328 * Internal method - should not be used anywhere.
329 * @deprecated since 2.6
330 * @return array $_POST.
332 protected function _get_post_params() {
337 * Internal method. Validates all old-style deprecated uploaded files.
338 * The new way is to upload files via repository api.
340 * @param array $files list of files to be validated
341 * @return bool|array Success or an array of errors
343 function _validate_files(&$files) {
344 global $CFG, $COURSE;
348 if (empty($_FILES)) {
349 // we do not need to do any checks because no files were submitted
350 // note: server side rules do not work for files - use custom verification in validate() instead
355 $filenames = array();
357 // now check that we really want each file
358 foreach ($_FILES as $elname=>$file) {
359 $required = $this->_form
->isElementRequired($elname);
361 if ($file['error'] == 4 and $file['size'] == 0) {
363 $errors[$elname] = get_string('required');
365 unset($_FILES[$elname]);
369 if (!empty($file['error'])) {
370 $errors[$elname] = file_get_upload_error($file['error']);
371 unset($_FILES[$elname]);
375 if (!is_uploaded_file($file['tmp_name'])) {
376 // TODO: improve error message
377 $errors[$elname] = get_string('error');
378 unset($_FILES[$elname]);
382 if (!$this->_form
->elementExists($elname) or !$this->_form
->getElementType($elname)=='file') {
383 // hmm, this file was not requested
384 unset($_FILES[$elname]);
388 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
390 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE
);
391 if ($filename === '') {
392 // TODO: improve error message - wrong chars
393 $errors[$elname] = get_string('error');
394 unset($_FILES[$elname]);
397 if (in_array($filename, $filenames)) {
398 // TODO: improve error message - duplicate name
399 $errors[$elname] = get_string('error');
400 unset($_FILES[$elname]);
403 $filenames[] = $filename;
404 $_FILES[$elname]['name'] = $filename;
406 $files[$elname] = $_FILES[$elname]['tmp_name'];
409 // return errors if found
410 if (count($errors) == 0){
420 * Internal method. Validates filepicker and filemanager files if they are
421 * set as required fields. Also, sets the error message if encountered one.
423 * @return bool|array with errors
425 protected function validate_draft_files() {
427 $mform =& $this->_form
;
430 //Go through all the required elements and make sure you hit filepicker or
431 //filemanager element.
432 foreach ($mform->_rules
as $elementname => $rules) {
433 $elementtype = $mform->getElementType($elementname);
434 //If element is of type filepicker then do validation
435 if (($elementtype == 'filepicker') ||
($elementtype == 'filemanager')){
436 //Check if rule defined is required rule
437 foreach ($rules as $rule) {
438 if ($rule['type'] == 'required') {
439 $draftid = (int)$mform->getSubmitValue($elementname);
440 $fs = get_file_storage();
441 $context = context_user
::instance($USER->id
);
442 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
443 $errors[$elementname] = $rule['message'];
449 // Check all the filemanager elements to make sure they do not have too many
451 foreach ($mform->_elements
as $element) {
452 if ($element->_type
== 'filemanager') {
453 $maxfiles = $element->getMaxfiles();
455 $draftid = (int)$element->getValue();
456 $fs = get_file_storage();
457 $context = context_user
::instance($USER->id
);
458 $files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, '', false);
459 if (count($files) > $maxfiles) {
460 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
465 if (empty($errors)) {
473 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
474 * form definition (new entry form); this function is used to load in data where values
475 * already exist and data is being edited (edit entry form).
477 * note: $slashed param removed
479 * @param stdClass|array $default_values object or array of default values
481 function set_data($default_values) {
482 if (is_object($default_values)) {
483 $default_values = (array)$default_values;
485 $this->_form
->setDefaults($default_values);
489 * Check that form was submitted. Does not check validity of submitted data.
491 * @return bool true if form properly submitted
493 function is_submitted() {
494 return $this->_form
->isSubmitted();
498 * Checks if button pressed is not for submitting the form
500 * @staticvar bool $nosubmit keeps track of no submit button
503 function no_submit_button_pressed(){
504 static $nosubmit = null; // one check is enough
505 if (!is_null($nosubmit)){
508 $mform =& $this->_form
;
510 if (!$this->is_submitted()){
513 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
514 if ($this->optional_param($nosubmitbutton, 0, PARAM_RAW
)) {
523 * Checks if a parameter was passed in the previous form submission
525 * @param string $name the name of the page parameter we want
526 * @param mixed $default the default value to return if nothing is found
527 * @param string $type expected type of parameter
530 public function optional_param($name, $default, $type) {
531 if (isset($this->_ajaxformdata
[$name])) {
532 return clean_param($this->_ajaxformdata
[$name], $type);
534 return optional_param($name, $default, $type);
539 * Check that form data is valid.
540 * You should almost always use this, rather than {@link validate_defined_fields}
542 * @return bool true if form data valid
544 function is_validated() {
545 //finalize the form definition before any processing
546 if (!$this->_definition_finalized
) {
547 $this->_definition_finalized
= true;
548 $this->definition_after_data();
551 return $this->validate_defined_fields();
557 * You almost always want to call {@link is_validated} instead of this
558 * because it calls {@link definition_after_data} first, before validating the form,
559 * which is what you want in 99% of cases.
561 * This is provided as a separate function for those special cases where
562 * you want the form validated before definition_after_data is called
563 * for example, to selectively add new elements depending on a no_submit_button press,
564 * but only when the form is valid when the no_submit_button is pressed,
566 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
567 * is NOT to validate the form when a no submit button has been pressed.
568 * pass true here to override this behaviour
570 * @return bool true if form data valid
572 function validate_defined_fields($validateonnosubmit=false) {
573 $mform =& $this->_form
;
574 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
576 } elseif ($this->_validated
=== null) {
577 $internal_val = $mform->validate();
580 $file_val = $this->_validate_files($files);
581 //check draft files for validation and flag them if required files
582 //are not in draft area.
583 $draftfilevalue = $this->validate_draft_files();
585 if ($file_val !== true && $draftfilevalue !== true) {
586 $file_val = array_merge($file_val, $draftfilevalue);
587 } else if ($draftfilevalue !== true) {
588 $file_val = $draftfilevalue;
589 } //default is file_val, so no need to assign.
591 if ($file_val !== true) {
592 if (!empty($file_val)) {
593 foreach ($file_val as $element=>$msg) {
594 $mform->setElementError($element, $msg);
600 // Give the elements a chance to perform an implicit validation.
602 foreach ($mform->_elements
as $element) {
603 if (method_exists($element, 'validateSubmitValue')) {
604 $value = $mform->getSubmitValue($element->getName());
605 $result = $element->validateSubmitValue($value);
606 if (!empty($result) && is_string($result)) {
607 $element_val = false;
608 $mform->setElementError($element->getName(), $result);
613 // Let the form instance validate the submitted values.
614 $data = $mform->exportValues();
615 $moodle_val = $this->validation($data, $files);
616 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
617 // non-empty array means errors
618 foreach ($moodle_val as $element=>$msg) {
619 $mform->setElementError($element, $msg);
624 // anything else means validation ok
628 $this->_validated
= ($internal_val and $element_val and $moodle_val and $file_val);
630 return $this->_validated
;
634 * Return true if a cancel button has been pressed resulting in the form being submitted.
636 * @return bool true if a cancel button has been pressed
638 function is_cancelled(){
639 $mform =& $this->_form
;
640 if ($mform->isSubmitted()){
641 foreach ($mform->_cancelButtons
as $cancelbutton){
642 if ($this->optional_param($cancelbutton, 0, PARAM_RAW
)) {
651 * Return submitted data if properly submitted or returns NULL if validation fails or
652 * if there is no submitted data.
654 * note: $slashed param removed
656 * @return object submitted data; NULL if not valid or not submitted or cancelled
658 function get_data() {
659 $mform =& $this->_form
;
661 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
662 $data = $mform->exportValues();
663 unset($data['sesskey']); // we do not need to return sesskey
664 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
668 return (object)$data;
676 * Return submitted data without validation or NULL if there is no submitted data.
677 * note: $slashed param removed
679 * @return object submitted data; NULL if not submitted
681 function get_submitted_data() {
682 $mform =& $this->_form
;
684 if ($this->is_submitted()) {
685 $data = $mform->exportValues();
686 unset($data['sesskey']); // we do not need to return sesskey
687 unset($data['_qf__'.$this->_formname
]); // we do not need the submission marker too
691 return (object)$data;
699 * Save verified uploaded files into directory. Upload process can be customised from definition()
701 * @deprecated since Moodle 2.0
702 * @todo MDL-31294 remove this api
703 * @see moodleform::save_stored_file()
704 * @see moodleform::save_file()
705 * @param string $destination path where file should be stored
706 * @return bool Always false
708 function save_files($destination) {
709 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
714 * Returns name of uploaded file.
716 * @param string $elname first element if null
717 * @return string|bool false in case of failure, string if ok
719 function get_new_filename($elname=null) {
722 if (!$this->is_submitted() or !$this->is_validated()) {
726 if (is_null($elname)) {
727 if (empty($_FILES)) {
731 $elname = key($_FILES);
734 if (empty($elname)) {
738 $element = $this->_form
->getElement($elname);
740 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
741 $values = $this->_form
->exportValues($elname);
742 if (empty($values[$elname])) {
745 $draftid = $values[$elname];
746 $fs = get_file_storage();
747 $context = context_user
::instance($USER->id
);
748 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
751 $file = reset($files);
752 return $file->get_filename();
755 if (!isset($_FILES[$elname])) {
759 return $_FILES[$elname]['name'];
763 * Save file to standard filesystem
765 * @param string $elname name of element
766 * @param string $pathname full path name of file
767 * @param bool $override override file if exists
768 * @return bool success
770 function save_file($elname, $pathname, $override=false) {
773 if (!$this->is_submitted() or !$this->is_validated()) {
776 if (file_exists($pathname)) {
778 if (!@unlink
($pathname)) {
786 $element = $this->_form
->getElement($elname);
788 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
789 $values = $this->_form
->exportValues($elname);
790 if (empty($values[$elname])) {
793 $draftid = $values[$elname];
794 $fs = get_file_storage();
795 $context = context_user
::instance($USER->id
);
796 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
799 $file = reset($files);
801 return $file->copy_content_to($pathname);
803 } else if (isset($_FILES[$elname])) {
804 return copy($_FILES[$elname]['tmp_name'], $pathname);
811 * Returns a temporary file, do not forget to delete after not needed any more.
813 * @param string $elname name of the elmenet
814 * @return string|bool either string or false
816 function save_temp_file($elname) {
817 if (!$this->get_new_filename($elname)) {
820 if (!$dir = make_temp_directory('forms')) {
823 if (!$tempfile = tempnam($dir, 'tempup_')) {
826 if (!$this->save_file($elname, $tempfile, true)) {
827 // something went wrong
836 * Get draft files of a form element
837 * This is a protected method which will be used only inside moodleforms
839 * @param string $elname name of element
840 * @return array|bool|null
842 protected function get_draft_files($elname) {
845 if (!$this->is_submitted()) {
849 $element = $this->_form
->getElement($elname);
851 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
852 $values = $this->_form
->exportValues($elname);
853 if (empty($values[$elname])) {
856 $draftid = $values[$elname];
857 $fs = get_file_storage();
858 $context = context_user
::instance($USER->id
);
859 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
868 * Save file to local filesystem pool
870 * @param string $elname name of element
871 * @param int $newcontextid id of context
872 * @param string $newcomponent name of the component
873 * @param string $newfilearea name of file area
874 * @param int $newitemid item id
875 * @param string $newfilepath path of file where it get stored
876 * @param string $newfilename use specified filename, if not specified name of uploaded file used
877 * @param bool $overwrite overwrite file if exists
878 * @param int $newuserid new userid if required
879 * @return mixed stored_file object or false if error; may throw exception if duplicate found
881 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
882 $newfilename=null, $overwrite=false, $newuserid=null) {
885 if (!$this->is_submitted() or !$this->is_validated()) {
889 if (empty($newuserid)) {
890 $newuserid = $USER->id
;
893 $element = $this->_form
->getElement($elname);
894 $fs = get_file_storage();
896 if ($element instanceof MoodleQuickForm_filepicker
) {
897 $values = $this->_form
->exportValues($elname);
898 if (empty($values[$elname])) {
901 $draftid = $values[$elname];
902 $context = context_user
::instance($USER->id
);
903 if (!$files = $fs->get_area_files($context->id
, 'user' ,'draft', $draftid, 'id DESC', false)) {
906 $file = reset($files);
907 if (is_null($newfilename)) {
908 $newfilename = $file->get_filename();
912 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
913 if (!$oldfile->delete()) {
919 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
920 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
921 return $fs->create_file_from_storedfile($file_record, $file);
923 } else if (isset($_FILES[$elname])) {
924 $filename = is_null($newfilename) ?
$_FILES[$elname]['name'] : $newfilename;
927 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
928 if (!$oldfile->delete()) {
934 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
935 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
936 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
943 * Get content of uploaded file.
945 * @param string $elname name of file upload element
946 * @return string|bool false in case of failure, string if ok
948 function get_file_content($elname) {
951 if (!$this->is_submitted() or !$this->is_validated()) {
955 $element = $this->_form
->getElement($elname);
957 if ($element instanceof MoodleQuickForm_filepicker ||
$element instanceof MoodleQuickForm_filemanager
) {
958 $values = $this->_form
->exportValues($elname);
959 if (empty($values[$elname])) {
962 $draftid = $values[$elname];
963 $fs = get_file_storage();
964 $context = context_user
::instance($USER->id
);
965 if (!$files = $fs->get_area_files($context->id
, 'user', 'draft', $draftid, 'id DESC', false)) {
968 $file = reset($files);
970 return $file->get_content();
972 } else if (isset($_FILES[$elname])) {
973 return file_get_contents($_FILES[$elname]['tmp_name']);
983 //finalize the form definition if not yet done
984 if (!$this->_definition_finalized
) {
985 $this->_definition_finalized
= true;
986 $this->definition_after_data();
989 $this->_form
->display();
993 * Renders the html form (same as display, but returns the result).
995 * Note that you can only output this rendered result once per page, as
996 * it contains IDs which must be unique.
998 * @return string HTML code for the form
1000 public function render() {
1003 $out = ob_get_contents();
1009 * Form definition. Abstract method - always override!
1011 protected abstract function definition();
1014 * After definition hook.
1016 * This is useful for intermediate classes to inject logic after the definition was
1017 * provided without requiring developers to call the parent {{@link self::definition()}}
1018 * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
1019 * IntermediateClass extends moodleform'.
1021 * Classes overriding this method should always call the parent. We may not add
1022 * anything specifically in this instance of the method, but intermediate classes
1023 * are likely to do so, and so it is a good practice to always call the parent.
1027 protected function after_definition() {
1031 * Dummy stub method - override if you need to setup the form depending on current
1032 * values. This method is called after definition(), data submission and set_data().
1033 * All form setup that is dependent on form values should go in here.
1035 function definition_after_data(){
1039 * Dummy stub method - override if you needed to perform some extra validation.
1040 * If there are errors return array of errors ("fieldname"=>"error message"),
1041 * otherwise true if ok.
1043 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1045 * @param array $data array of ("fieldname"=>value) of submitted data
1046 * @param array $files array of uploaded files "element_name"=>tmp_file_path
1047 * @return array of "element_name"=>"error_description" if there are errors,
1048 * or an empty array if everything is OK (true allowed for backwards compatibility too).
1050 function validation($data, $files) {
1055 * Helper used by {@link repeat_elements()}.
1057 * @param int $i the index of this element.
1058 * @param HTML_QuickForm_element $elementclone
1059 * @param array $namecloned array of names
1061 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1062 $name = $elementclone->getName();
1063 $namecloned[] = $name;
1065 if (!empty($name)) {
1066 $elementclone->setName($name."[$i]");
1069 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1070 $value = $elementclone->_text
;
1071 $elementclone->setValue(str_replace('{no}', ($i+
1), $value));
1073 } else if (is_a($elementclone, 'HTML_QuickForm_submit') ||
is_a($elementclone, 'HTML_QuickForm_button')) {
1074 $elementclone->setValue(str_replace('{no}', ($i+
1), $elementclone->getValue()));
1077 $value=$elementclone->getLabel();
1078 $elementclone->setLabel(str_replace('{no}', ($i+
1), $value));
1083 * Method to add a repeating group of elements to a form.
1085 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1086 * @param int $repeats no of times to repeat elements initially
1087 * @param array $options a nested array. The first array key is the element name.
1088 * the second array key is the type of option to set, and depend on that option,
1089 * the value takes different forms.
1090 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1091 * 'type' - PARAM_* type.
1092 * 'helpbutton' - array containing the helpbutton params.
1093 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1094 * 'rule' - array containing the addRule arguments after the element name.
1095 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1096 * 'advanced' - whether this element is hidden by 'Show more ...'.
1097 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1098 * @param string $addfieldsname name for button to add more fields
1099 * @param int $addfieldsno how many fields to add at a time
1100 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1101 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1102 * @return int no of repeats of element in this page
1104 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1105 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1106 if ($addstring===null){
1107 $addstring = get_string('addfields', 'form', $addfieldsno);
1109 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1111 $repeats = $this->optional_param($repeathiddenname, $repeats, PARAM_INT
);
1112 $addfields = $this->optional_param($addfieldsname, '', PARAM_TEXT
);
1113 if (!empty($addfields)){
1114 $repeats +
= $addfieldsno;
1116 $mform =& $this->_form
;
1117 $mform->registerNoSubmitButton($addfieldsname);
1118 $mform->addElement('hidden', $repeathiddenname, $repeats);
1119 $mform->setType($repeathiddenname, PARAM_INT
);
1120 //value not to be overridden by submitted value
1121 $mform->setConstants(array($repeathiddenname=>$repeats));
1122 $namecloned = array();
1123 for ($i = 0; $i < $repeats; $i++
) {
1124 foreach ($elementobjs as $elementobj){
1125 $elementclone = fullclone($elementobj);
1126 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1128 if ($elementclone instanceof HTML_QuickForm_group
&& !$elementclone->_appendName
) {
1129 foreach ($elementclone->getElements() as $el) {
1130 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1132 $elementclone->setLabel(str_replace('{no}', $i +
1, $elementclone->getLabel()));
1135 $mform->addElement($elementclone);
1138 for ($i=0; $i<$repeats; $i++
) {
1139 foreach ($options as $elementname => $elementoptions){
1140 $pos=strpos($elementname, '[');
1142 $realelementname = substr($elementname, 0, $pos)."[$i]";
1143 $realelementname .= substr($elementname, $pos);
1145 $realelementname = $elementname."[$i]";
1147 foreach ($elementoptions as $option => $params){
1151 $mform->setDefault($realelementname, str_replace('{no}', $i +
1, $params));
1154 $params = array_merge(array($realelementname), $params);
1155 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1158 foreach ($namecloned as $num => $name){
1159 if ($params[0] == $name){
1160 $params[0] = $params[0]."[$i]";
1164 $params = array_merge(array($realelementname), $params);
1165 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1168 foreach ($namecloned as $num => $name){
1169 if ($params[0] == $name){
1170 $params[0] = $params[0]."[$i]";
1174 $params = array_merge(array($realelementname), $params);
1175 call_user_func_array(array(&$mform, 'hideIf'), $params);
1178 if (is_string($params)){
1179 $params = array(null, $params, null, 'client');
1181 $params = array_merge(array($realelementname), $params);
1182 call_user_func_array(array(&$mform, 'addRule'), $params);
1186 $mform->setType($realelementname, $params);
1190 $mform->setExpanded($realelementname, $params);
1194 $mform->setAdvanced($realelementname, $params);
1200 $mform->addElement('submit', $addfieldsname, $addstring);
1202 if (!$addbuttoninside) {
1203 $mform->closeHeaderBefore($addfieldsname);
1210 * Adds a link/button that controls the checked state of a group of checkboxes.
1212 * @param int $groupid The id of the group of advcheckboxes this element controls
1213 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1214 * @param array $attributes associative array of HTML attributes
1215 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1217 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1220 // Name of the controller button
1221 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1222 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1223 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1225 // Set the default text if none was specified
1227 $text = get_string('selectallornone', 'form');
1230 $mform = $this->_form
;
1231 $selectvalue = $this->optional_param($checkboxcontrollerparam, null, PARAM_INT
);
1232 $contollerbutton = $this->optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT
);
1234 $newselectvalue = $selectvalue;
1235 if (is_null($selectvalue)) {
1236 $newselectvalue = $originalValue;
1237 } else if (!is_null($contollerbutton)) {
1238 $newselectvalue = (int) !$selectvalue;
1240 // set checkbox state depending on orignal/submitted value by controoler button
1241 if (!is_null($contollerbutton) ||
is_null($selectvalue)) {
1242 foreach ($mform->_elements
as $element) {
1243 if (($element instanceof MoodleQuickForm_advcheckbox
) &&
1244 $element->getAttribute('class') == $checkboxgroupclass &&
1245 !$element->isFrozen()) {
1246 $mform->setConstants(array($element->getName() => $newselectvalue));
1251 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1252 $mform->setType($checkboxcontrollerparam, PARAM_INT
);
1253 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1255 $PAGE->requires
->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1257 array('groupid' => $groupid,
1258 'checkboxclass' => $checkboxgroupclass,
1259 'checkboxcontroller' => $checkboxcontrollerparam,
1260 'controllerbutton' => $checkboxcontrollername)
1264 require_once("$CFG->libdir/form/submit.php");
1265 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1266 $mform->addElement($submitlink);
1267 $mform->registerNoSubmitButton($checkboxcontrollername);
1268 $mform->setDefault($checkboxcontrollername, $text);
1272 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1273 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1274 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1275 * get data with get_data().
1277 * @param bool $cancel whether to show cancel button, default true
1278 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1280 function add_action_buttons($cancel = true, $submitlabel=null){
1281 if (is_null($submitlabel)){
1282 $submitlabel = get_string('savechanges');
1284 $mform =& $this->_form
;
1286 //when two elements we need a group
1287 $buttonarray=array();
1288 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1289 $buttonarray[] = &$mform->createElement('cancel');
1290 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1291 $mform->closeHeaderBefore('buttonar');
1294 $mform->addElement('submit', 'submitbutton', $submitlabel);
1295 $mform->closeHeaderBefore('submitbutton');
1300 * Adds an initialisation call for a standard JavaScript enhancement.
1302 * This function is designed to add an initialisation call for a JavaScript
1303 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1307 * - smartselect: Turns a nbsp indented select box into a custom drop down
1308 * control that supports multilevel and category selection.
1309 * $enhancement = 'smartselect';
1310 * $options = array('selectablecategories' => true|false)
1312 * @param string|element $element form element for which Javascript needs to be initalized
1313 * @param string $enhancement which init function should be called
1314 * @param array $options options passed to javascript
1315 * @param array $strings strings for javascript
1316 * @deprecated since Moodle 3.3 MDL-57471
1318 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1319 debugging('$mform->init_javascript_enhancement() is deprecated and no longer does anything. '.
1320 'smartselect uses should be converted to the searchableselector form element.', DEBUG_DEVELOPER
);
1324 * Returns a JS module definition for the mforms JS
1328 public static function get_js_module() {
1332 'fullpath' => '/lib/form/form.js',
1333 'requires' => array('base', 'node')
1338 * Detects elements with missing setType() declerations.
1340 * Finds elements in the form which should a PARAM_ type set and throws a
1341 * developer debug warning for any elements without it. This is to reduce the
1342 * risk of potential security issues by developers mistakenly forgetting to set
1347 private function detectMissingSetType() {
1350 if (!$CFG->debugdeveloper
) {
1355 $mform = $this->_form
;
1356 foreach ($mform->_elements
as $element) {
1358 $elements = array($element);
1360 if ($element->getType() == 'group') {
1362 $elements = $element->getElements();
1365 foreach ($elements as $index => $element) {
1366 switch ($element->getType()) {
1371 $name = $group->getElementName($index);
1373 $name = $element->getName();
1376 $found = array_key_exists($key, $mform->_types
);
1377 // For repeated elements we need to look for
1378 // the "main" type, not for the one present
1379 // on each repetition. All the stuff in formslib
1380 // (repeat_elements(), updateSubmission()... seems
1381 // to work that way.
1382 while (!$found && strrpos($key, '[') !== false) {
1383 $pos = strrpos($key, '[');
1384 $key = substr($key, 0, $pos);
1385 $found = array_key_exists($key, $mform->_types
);
1388 debugging("Did you remember to call setType() for '$name'? ".
1389 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER
);
1398 * Used by tests to simulate submitted form data submission from the user.
1400 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1403 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1404 * global arrays after each test.
1406 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1407 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1408 * @param string $method 'post' or 'get', defaults to 'post'.
1409 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1410 * a different value here for some forms that are used more than once on the
1413 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1414 $formidentifier = null) {
1415 $_FILES = $simulatedsubmittedfiles;
1416 if ($formidentifier === null) {
1417 $formidentifier = get_called_class();
1418 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1420 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1421 $simulatedsubmitteddata['sesskey'] = sesskey();
1422 if (strtolower($method) === 'get') {
1423 $_GET = $simulatedsubmitteddata;
1425 $_POST = $simulatedsubmitteddata;
1430 * Used by tests to generate valid submit keys for moodle forms that are
1431 * submitted with ajax data.
1433 * @throws \moodle_exception If called outside unit test environment
1434 * @param array $data Existing form data you wish to add the keys to.
1437 public static function mock_generate_submit_keys($data = []) {
1438 if (!defined('PHPUNIT_TEST') ||
!PHPUNIT_TEST
) {
1439 throw new \
moodle_exception("This function can only be used for unit testing.");
1442 $formidentifier = get_called_class();
1443 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1444 $data['sesskey'] = sesskey();
1445 $data['_qf__' . $formidentifier] = 1;
1451 * Set display mode for the form when labels take full width of the form and above the elements even on big screens
1453 * Useful for forms displayed inside modals or in narrow containers
1455 public function set_display_vertical() {
1456 $oldclass = $this->_form
->getAttribute('class');
1457 $this->_form
->updateAttributes(array('class' => $oldclass . ' full-width-labels'));
1461 * Set the initial 'dirty' state of the form.
1463 * @param bool $state
1464 * @since Moodle 3.7.1
1466 public function set_initial_dirty_state($state = false) {
1467 $this->_form
->set_initial_dirty_state($state);
1472 * MoodleQuickForm implementation
1474 * You never extend this class directly. The class methods of this class are available from
1475 * the private $this->_form property on moodleform and its children. You generally only
1476 * call methods on this class from within abstract methods that you override on moodleform such
1477 * as definition and definition_after_data
1479 * @package core_form
1481 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1484 class MoodleQuickForm
extends HTML_QuickForm_DHTMLRulesTableless
{
1485 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1486 var $_types = array();
1488 /** @var array dependent state for the element/'s */
1489 var $_dependencies = array();
1492 * @var array elements that will become hidden based on another element
1494 protected $_hideifs = array();
1496 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1497 var $_noSubmitButtons=array();
1499 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1500 var $_cancelButtons=array();
1502 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1503 var $_advancedElements = array();
1506 * Array whose keys are element names and values are the desired collapsible state.
1507 * True for collapsed, False for expanded. If not present, set to default in
1508 * {@link self::accept()}.
1512 var $_collapsibleElements = array();
1515 * Whether to enable shortforms for this form
1519 var $_disableShortforms = false;
1521 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1522 protected $_use_form_change_checker = true;
1525 * The initial state of the dirty state.
1529 protected $_initial_form_dirty_state = false;
1532 * The form name is derived from the class name of the wrapper minus the trailing form
1533 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1536 var $_formName = '';
1539 * String with the html for hidden params passed in as part of a moodle_url
1540 * object for the action. Output in the form.
1543 var $_pageparams = '';
1545 /** @var array $_ajaxformdata submitted form data when using mforms with ajax */
1546 protected $_ajaxformdata;
1549 * Whether the form contains any client-side validation or not.
1552 protected $clientvalidation = false;
1555 * Is this a 'disableIf' dependency ?
1557 const DEP_DISABLE
= 0;
1560 * Is this a 'hideIf' dependency?
1565 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1567 * @staticvar int $formcounter counts number of forms
1568 * @param string $formName Form's name.
1569 * @param string $method Form's method defaults to 'POST'
1570 * @param string|moodle_url $action Form's action
1571 * @param string $target (optional)Form's target defaults to none
1572 * @param mixed $attributes (optional)Extra attributes for <form> tag
1573 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
1575 public function __construct($formName, $method, $action, $target = '', $attributes = null, $ajaxformdata = null) {
1576 global $CFG, $OUTPUT;
1578 static $formcounter = 1;
1580 // TODO MDL-52313 Replace with the call to parent::__construct().
1581 HTML_Common
::__construct($attributes);
1582 $target = empty($target) ?
array() : array('target' => $target);
1583 $this->_formName
= $formName;
1584 if (is_a($action, 'moodle_url')){
1585 $this->_pageparams
= html_writer
::input_hidden_params($action);
1586 $action = $action->out_omit_querystring();
1588 $this->_pageparams
= '';
1590 // No 'name' atttribute for form in xhtml strict :
1591 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') +
$target;
1592 if (is_null($this->getAttribute('id'))) {
1593 // Append a random id, forms can be loaded in different requests using Fragments API.
1594 $attributes['id'] = 'mform' . $formcounter . '_' . random_string();
1597 $this->updateAttributes($attributes);
1599 // This is custom stuff for Moodle :
1600 $this->_ajaxformdata
= $ajaxformdata;
1601 $oldclass= $this->getAttribute('class');
1602 if (!empty($oldclass)){
1603 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1605 $this->updateAttributes(array('class'=>'mform'));
1607 $this->_reqHTML
= '<span class="req">' . $OUTPUT->pix_icon('req', get_string('requiredelement', 'form')) . '</span>';
1608 $this->_advancedHTML
= '<span class="adv">' . $OUTPUT->pix_icon('adv', get_string('advancedelement', 'form')) . '</span>';
1609 $this->setRequiredNote(get_string('somefieldsrequired', 'form', $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'))));
1613 * Old syntax of class constructor. Deprecated in PHP7.
1615 * @deprecated since Moodle 3.1
1617 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1618 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
1619 self
::__construct($formName, $method, $action, $target, $attributes);
1623 * Use this method to indicate an element in a form is an advanced field. If items in a form
1624 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1625 * form so the user can decide whether to display advanced form controls.
1627 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1629 * @param string $elementName group or element name (not the element name of something inside a group).
1630 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1632 function setAdvanced($elementName, $advanced = true) {
1634 $this->_advancedElements
[$elementName]='';
1635 } elseif (isset($this->_advancedElements
[$elementName])) {
1636 unset($this->_advancedElements
[$elementName]);
1641 * Checks if a parameter was passed in the previous form submission
1643 * @param string $name the name of the page parameter we want
1644 * @param mixed $default the default value to return if nothing is found
1645 * @param string $type expected type of parameter
1648 public function optional_param($name, $default, $type) {
1649 if (isset($this->_ajaxformdata
[$name])) {
1650 return clean_param($this->_ajaxformdata
[$name], $type);
1652 return optional_param($name, $default, $type);
1657 * Use this method to indicate that the fieldset should be shown as expanded.
1658 * The method is applicable to header elements only.
1660 * @param string $headername header element name
1661 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1662 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1663 * the form was submitted.
1666 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1667 if (empty($headername)) {
1670 $element = $this->getElement($headername);
1671 if ($element->getType() != 'header') {
1672 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER
);
1675 if (!$headerid = $element->getAttribute('id')) {
1676 $element->_generateId();
1677 $headerid = $element->getAttribute('id');
1679 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1680 // See if the form has been submitted already.
1681 $formexpanded = $this->optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT
);
1682 if (!$ignoreuserstate && $formexpanded != -1) {
1683 // Override expanded state with the form variable.
1684 $expanded = $formexpanded;
1686 // Create the form element for storing expanded state.
1687 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1688 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT
);
1689 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1691 $this->_collapsibleElements
[$headername] = !$expanded;
1695 * Use this method to add show more/less status element required for passing
1696 * over the advanced elements visibility status on the form submission.
1698 * @param string $headerName header element name.
1699 * @param boolean $showmore default false sets the advanced elements to be hidden.
1701 function addAdvancedStatusElement($headerid, $showmore=false){
1702 // Add extra hidden element to store advanced items state for each section.
1703 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1704 // See if we the form has been submitted already.
1705 $formshowmore = $this->optional_param('mform_showmore_' . $headerid, -1, PARAM_INT
);
1706 if (!$showmore && $formshowmore != -1) {
1707 // Override showmore state with the form variable.
1708 $showmore = $formshowmore;
1710 // Create the form element for storing advanced items state.
1711 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1712 $this->setType('mform_showmore_' . $headerid, PARAM_INT
);
1713 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1718 * This function has been deprecated. Show advanced has been replaced by
1719 * "Show more.../Show less..." in the shortforms javascript module.
1721 * @deprecated since Moodle 2.5
1722 * @param bool $showadvancedNow if true will show advanced elements.
1724 function setShowAdvanced($showadvancedNow = null){
1725 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1729 * This function has been deprecated. Show advanced has been replaced by
1730 * "Show more.../Show less..." in the shortforms javascript module.
1732 * @deprecated since Moodle 2.5
1733 * @return bool (Always false)
1735 function getShowAdvanced(){
1736 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1741 * Use this method to indicate that the form will not be using shortforms.
1743 * @param boolean $disable default true, controls if the shortforms are disabled.
1745 function setDisableShortforms ($disable = true) {
1746 $this->_disableShortforms
= $disable;
1750 * Set the initial 'dirty' state of the form.
1752 * @param bool $state
1753 * @since Moodle 3.7.1
1755 public function set_initial_dirty_state($state = false) {
1756 $this->_initial_form_dirty_state
= $state;
1760 * Is the form currently set to dirty?
1762 * @return boolean Initial dirty state.
1763 * @since Moodle 3.7.1
1765 public function is_dirty() {
1766 return $this->_initial_form_dirty_state
;
1770 * Call this method if you don't want the formchangechecker JavaScript to be
1771 * automatically initialised for this form.
1773 public function disable_form_change_checker() {
1774 $this->_use_form_change_checker
= false;
1778 * If you have called {@link disable_form_change_checker()} then you can use
1779 * this method to re-enable it. It is enabled by default, so normally you don't
1780 * need to call this.
1782 public function enable_form_change_checker() {
1783 $this->_use_form_change_checker
= true;
1787 * @return bool whether this form should automatically initialise
1788 * formchangechecker for itself.
1790 public function is_form_change_checker_enabled() {
1791 return $this->_use_form_change_checker
;
1795 * Accepts a renderer
1797 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1799 function accept(&$renderer) {
1800 if (method_exists($renderer, 'setAdvancedElements')){
1801 //Check for visible fieldsets where all elements are advanced
1802 //and mark these headers as advanced as well.
1803 //Also mark all elements in a advanced header as advanced.
1804 $stopFields = $renderer->getStopFieldSetElements();
1806 $lastHeaderAdvanced = false;
1807 $anyAdvanced = false;
1809 foreach (array_keys($this->_elements
) as $elementIndex){
1810 $element =& $this->_elements
[$elementIndex];
1812 // if closing header and any contained element was advanced then mark it as advanced
1813 if ($element->getType()=='header' ||
in_array($element->getName(), $stopFields)){
1814 if ($anyAdvanced && !is_null($lastHeader)) {
1815 $lastHeader->_generateId();
1816 $this->setAdvanced($lastHeader->getName());
1817 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1819 $lastHeaderAdvanced = false;
1822 } elseif ($lastHeaderAdvanced) {
1823 $this->setAdvanced($element->getName());
1826 if ($element->getType()=='header'){
1827 $lastHeader =& $element;
1828 $anyAdvanced = false;
1830 $lastHeaderAdvanced = isset($this->_advancedElements
[$element->getName()]);
1831 } elseif (isset($this->_advancedElements
[$element->getName()])){
1832 $anyAdvanced = true;
1833 if (isset($this->_errors
[$element->getName()])) {
1838 // the last header may not be closed yet...
1839 if ($anyAdvanced && !is_null($lastHeader)){
1840 $this->setAdvanced($lastHeader->getName());
1841 $lastHeader->_generateId();
1842 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1844 $renderer->setAdvancedElements($this->_advancedElements
);
1846 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms
) {
1848 // Count the number of sections.
1850 foreach (array_keys($this->_elements
) as $elementIndex){
1851 $element =& $this->_elements
[$elementIndex];
1852 if ($element->getType() == 'header') {
1857 $anyrequiredorerror = false;
1860 foreach (array_keys($this->_elements
) as $elementIndex){
1861 $element =& $this->_elements
[$elementIndex];
1863 if ($element->getType() == 'header') {
1865 $element->_generateId();
1866 $headername = $element->getName();
1867 $anyrequiredorerror = false;
1868 } else if (in_array($element->getName(), $this->_required
) ||
isset($this->_errors
[$element->getName()])) {
1869 $anyrequiredorerror = true;
1871 // Do not reset $anyrequiredorerror to false because we do not want any other element
1872 // in this header (fieldset) to possibly revert the state given.
1875 if ($element->getType() == 'header') {
1876 if ($headercounter === 1 && !isset($this->_collapsibleElements
[$headername])) {
1877 // By default the first section is always expanded, except if a state has already been set.
1878 $this->setExpanded($headername, true);
1879 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements
[$headername])) {
1880 // The second section is always expanded if the form only contains 2 sections),
1881 // except if a state has already been set.
1882 $this->setExpanded($headername, true);
1884 } else if ($anyrequiredorerror) {
1885 // If any error or required field are present within the header, we need to expand it.
1886 $this->setExpanded($headername, true, true);
1887 } else if (!isset($this->_collapsibleElements
[$headername])) {
1888 // Define element as collapsed by default.
1889 $this->setExpanded($headername, false);
1893 // Pass the array to renderer object.
1894 $renderer->setCollapsibleElements($this->_collapsibleElements
);
1896 parent
::accept($renderer);
1900 * Adds one or more element names that indicate the end of a fieldset
1902 * @param string $elementName name of the element
1904 function closeHeaderBefore($elementName){
1905 $renderer =& $this->defaultRenderer();
1906 $renderer->addStopFieldsetElements($elementName);
1910 * Set an element to be forced to flow LTR.
1912 * The element must exist and support this functionality. Also note that
1913 * when setting the type of a field (@link self::setType} we try to guess the
1914 * whether the field should be force to LTR or not. Make sure you're always
1915 * calling this method last.
1917 * @param string $elementname The element name.
1918 * @param bool $value When false, disables force LTR, else enables it.
1920 public function setForceLtr($elementname, $value = true) {
1921 $this->getElement($elementname)->set_force_ltr($value);
1925 * Should be used for all elements of a form except for select, radio and checkboxes which
1926 * clean their own data.
1928 * @param string $elementname
1929 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1930 * {@link lib/moodlelib.php} for defined parameter types
1932 function setType($elementname, $paramtype) {
1933 $this->_types
[$elementname] = $paramtype;
1935 // This will not always get it right, but it should be accurate in most cases.
1936 // When inaccurate use setForceLtr().
1937 if (!is_rtl_compatible($paramtype)
1938 && $this->elementExists($elementname)
1939 && ($element =& $this->getElement($elementname))
1940 && method_exists($element, 'set_force_ltr')) {
1942 $element->set_force_ltr(true);
1947 * This can be used to set several types at once.
1949 * @param array $paramtypes types of parameters.
1950 * @see MoodleQuickForm::setType
1952 function setTypes($paramtypes) {
1953 foreach ($paramtypes as $elementname => $paramtype) {
1954 $this->setType($elementname, $paramtype);
1959 * Return the type(s) to use to clean an element.
1961 * In the case where the element has an array as a value, we will try to obtain a
1962 * type defined for that specific key, and recursively until done.
1964 * This method does not work reverse, you cannot pass a nested element and hoping to
1965 * fallback on the clean type of a parent. This method intends to be used with the
1966 * main element, which will generate child types if needed, not the other way around.
1970 * You have defined a new repeated element containing a text field called 'foo'.
1971 * By default there will always be 2 occurence of 'foo' in the form. Even though
1972 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1973 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1974 * $mform->setType('foo[0]', PARAM_FLOAT).
1976 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1977 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1978 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1979 * get the default clean type returned (param $default).
1981 * @param string $elementname name of the element.
1982 * @param mixed $value value that should be cleaned.
1983 * @param int $default default constant value to be returned (PARAM_...)
1984 * @return string|array constant value or array of constant values (PARAM_...)
1986 public function getCleanType($elementname, $value, $default = PARAM_RAW
) {
1988 if (array_key_exists($elementname, $this->_types
)) {
1989 $type = $this->_types
[$elementname];
1991 if (is_array($value)) {
1994 foreach ($value as $subkey => $subvalue) {
1995 $typekey = "$elementname" . "[$subkey]";
1996 if (array_key_exists($typekey, $this->_types
)) {
1997 $subtype = $this->_types
[$typekey];
1999 $subtype = $default;
2001 if (is_array($subvalue)) {
2002 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
2004 $type[$subkey] = $subtype;
2012 * Return the cleaned value using the passed type(s).
2014 * @param mixed $value value that has to be cleaned.
2015 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
2016 * @return mixed cleaned up value.
2018 public function getCleanedValue($value, $type) {
2019 if (is_array($type) && is_array($value)) {
2020 foreach ($type as $key => $param) {
2021 $value[$key] = $this->getCleanedValue($value[$key], $param);
2023 } else if (!is_array($type) && !is_array($value)) {
2024 $value = clean_param($value, $type);
2025 } else if (!is_array($type) && is_array($value)) {
2026 $value = clean_param_array($value, $type, true);
2028 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
2034 * Updates submitted values
2036 * @param array $submission submitted values
2037 * @param array $files list of files
2039 function updateSubmission($submission, $files) {
2040 $this->_flagSubmitted
= false;
2042 if (empty($submission)) {
2043 $this->_submitValues
= array();
2045 foreach ($submission as $key => $s) {
2046 $type = $this->getCleanType($key, $s);
2047 $submission[$key] = $this->getCleanedValue($s, $type);
2049 $this->_submitValues
= $submission;
2050 $this->_flagSubmitted
= true;
2053 if (empty($files)) {
2054 $this->_submitFiles
= array();
2056 $this->_submitFiles
= $files;
2057 $this->_flagSubmitted
= true;
2060 // need to tell all elements that they need to update their value attribute.
2061 foreach (array_keys($this->_elements
) as $key) {
2062 $this->_elements
[$key]->onQuickFormEvent('updateValue', null, $this);
2067 * Returns HTML for required elements
2071 function getReqHTML(){
2072 return $this->_reqHTML
;
2076 * Returns HTML for advanced elements
2080 function getAdvancedHTML(){
2081 return $this->_advancedHTML
;
2085 * Initializes a default form value. Used to specify the default for a new entry where
2086 * no data is loaded in using moodleform::set_data()
2088 * note: $slashed param removed
2090 * @param string $elementName element name
2091 * @param mixed $defaultValue values for that element name
2093 function setDefault($elementName, $defaultValue){
2094 $this->setDefaults(array($elementName=>$defaultValue));
2098 * Add a help button to element, only one button per element is allowed.
2100 * This is new, simplified and preferable method of setting a help icon on form elements.
2101 * It uses the new $OUTPUT->help_icon().
2103 * Typically, you will provide the same identifier and the component as you have used for the
2104 * label of the element. The string identifier with the _help suffix added is then used
2105 * as the help string.
2107 * There has to be two strings defined:
2108 * 1/ get_string($identifier, $component) - the title of the help page
2109 * 2/ get_string($identifier.'_help', $component) - the actual help page text
2112 * @param string $elementname name of the element to add the item to
2113 * @param string $identifier help string identifier without _help suffix
2114 * @param string $component component name to look the help string in
2115 * @param string $linktext optional text to display next to the icon
2116 * @param bool $suppresscheck set to true if the element may not exist
2118 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
2120 if (array_key_exists($elementname, $this->_elementIndex
)) {
2121 $element = $this->_elements
[$this->_elementIndex
[$elementname]];
2122 $element->_helpbutton
= $OUTPUT->help_icon($identifier, $component, $linktext);
2123 } else if (!$suppresscheck) {
2124 debugging(get_string('nonexistentformelements', 'form', $elementname));
2129 * Set constant value not overridden by _POST or _GET
2130 * note: this does not work for complex names with [] :-(
2132 * @param string $elname name of element
2133 * @param mixed $value
2135 function setConstant($elname, $value) {
2136 $this->_constantValues
= HTML_QuickForm
::arrayMerge($this->_constantValues
, array($elname=>$value));
2137 $element =& $this->getElement($elname);
2138 $element->onQuickFormEvent('updateValue', null, $this);
2142 * export submitted values
2144 * @param string $elementList list of elements in form
2147 function exportValues($elementList = null){
2148 $unfiltered = array();
2149 if (null === $elementList) {
2150 // iterate over all elements, calling their exportValue() methods
2151 foreach (array_keys($this->_elements
) as $key) {
2152 if ($this->_elements
[$key]->isFrozen() && !$this->_elements
[$key]->_persistantFreeze
) {
2153 $varname = $this->_elements
[$key]->_attributes
['name'];
2155 // If we have a default value then export it.
2156 if (isset($this->_defaultValues
[$varname])) {
2157 $value = $this->prepare_fixed_value($varname, $this->_defaultValues
[$varname]);
2160 $value = $this->_elements
[$key]->exportValue($this->_submitValues
, true);
2163 if (is_array($value)) {
2164 // This shit throws a bogus warning in PHP 4.3.x
2165 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
2169 if (!is_array($elementList)) {
2170 $elementList = array_map('trim', explode(',', $elementList));
2172 foreach ($elementList as $elementName) {
2173 $value = $this->exportValue($elementName);
2174 if (@PEAR
::isError($value)) {
2177 //oh, stock QuickFOrm was returning array of arrays!
2178 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $value);
2182 if (is_array($this->_constantValues
)) {
2183 $unfiltered = HTML_QuickForm
::arrayMerge($unfiltered, $this->_constantValues
);
2189 * This is a bit of a hack, and it duplicates the code in
2190 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2191 * reliably calling that code. (Think about date selectors, for example.)
2192 * @param string $name the element name.
2193 * @param mixed $value the fixed value to set.
2194 * @return mixed the appropriate array to add to the $unfiltered array.
2196 protected function prepare_fixed_value($name, $value) {
2197 if (null === $value) {
2200 if (!strpos($name, '[')) {
2201 return array($name => $value);
2203 $valueAry = array();
2204 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2205 eval("\$valueAry$myIndex = \$value;");
2212 * Adds a validation rule for the given field
2214 * If the element is in fact a group, it will be considered as a whole.
2215 * To validate grouped elements as separated entities,
2216 * use addGroupRule instead of addRule.
2218 * @param string $element Form element name
2219 * @param string $message Message to display for invalid data
2220 * @param string $type Rule type, use getRegisteredRules() to get types
2221 * @param string $format (optional)Required for extra rule data
2222 * @param string $validation (optional)Where to perform validation: "server", "client"
2223 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2224 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2226 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2228 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
2229 if ($validation == 'client') {
2230 $this->clientvalidation
= true;
2236 * Adds a validation rule for the given group of elements
2238 * Only groups with a name can be assigned a validation rule
2239 * Use addGroupRule when you need to validate elements inside the group.
2240 * Use addRule if you need to validate the group as a whole. In this case,
2241 * the same rule will be applied to all elements in the group.
2242 * Use addRule if you need to validate the group against a function.
2244 * @param string $group Form group name
2245 * @param array|string $arg1 Array for multiple elements or error message string for one element
2246 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2247 * @param string $format (optional)Required for extra rule data
2248 * @param int $howmany (optional)How many valid elements should be in the group
2249 * @param string $validation (optional)Where to perform validation: "server", "client"
2250 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2252 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2254 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2255 if (is_array($arg1)) {
2256 foreach ($arg1 as $rules) {
2257 foreach ($rules as $rule) {
2258 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
2259 if ($validation == 'client') {
2260 $this->clientvalidation
= true;
2264 } elseif (is_string($arg1)) {
2265 if ($validation == 'client') {
2266 $this->clientvalidation
= true;
2272 * Returns the client side validation script
2274 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2275 * and slightly modified to run rules per-element
2276 * Needed to override this because of an error with client side validation of grouped elements.
2278 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2280 function getValidationScript()
2284 if (empty($this->_rules
) ||
$this->clientvalidation
=== false) {
2288 include_once('HTML/QuickForm/RuleRegistry.php');
2289 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
2300 foreach ($this->_rules
as $elementName => $rules) {
2301 foreach ($rules as $rule) {
2302 if ('client' == $rule['validation']) {
2303 unset($element); //TODO: find out how to properly initialize it
2305 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2306 $rule['message'] = strtr($rule['message'], $js_escape);
2308 if (isset($rule['group'])) {
2309 $group =& $this->getElement($rule['group']);
2310 // No JavaScript validation for frozen elements
2311 if ($group->isFrozen()) {
2314 $elements =& $group->getElements();
2315 foreach (array_keys($elements) as $key) {
2316 if ($elementName == $group->getElementName($key)) {
2317 $element =& $elements[$key];
2321 } elseif ($dependent) {
2323 $element[] =& $this->getElement($elementName);
2324 foreach ($rule['dependent'] as $elName) {
2325 $element[] =& $this->getElement($elName);
2328 $element =& $this->getElement($elementName);
2330 // No JavaScript validation for frozen elements
2331 if (is_object($element) && $element->isFrozen()) {
2333 } elseif (is_array($element)) {
2334 foreach (array_keys($element) as $key) {
2335 if ($element[$key]->isFrozen()) {
2340 //for editor element, [text] is appended to the name.
2341 $fullelementname = $elementName;
2342 if (is_object($element) && $element->getType() == 'editor') {
2343 if ($element->getType() == 'editor') {
2344 $fullelementname .= '[text]';
2345 // Add format to rule as moodleform check which format is supported by browser
2346 // it is not set anywhere... So small hack to make sure we pass it down to quickform.
2347 if (is_null($rule['format'])) {
2348 $rule['format'] = $element->getFormat();
2352 // Fix for bug displaying errors for elements in a group
2353 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2354 $test[$fullelementname][1]=$element;
2360 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2361 // the form, and then that form field gets corrupted by the code that follows.
2366 require(["core/event", "jquery"], function(Event, $) {
2368 function qf_errorHandler(element, _qfMsg, escapedName) {
2369 var event = $.Event(Event.Events.FORM_FIELD_VALIDATION);
2370 $(element).trigger(event, _qfMsg);
2371 if (event.isDefaultPrevented()) {
2372 return _qfMsg == \'\';
2375 var div = element.parentNode;
2377 if ((div == undefined) || (element.name == undefined)) {
2378 // No checking can be done for undefined elements so let server handle it.
2382 if (_qfMsg != \'\') {
2383 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2385 errorSpan = document.createElement("span");
2386 errorSpan.id = \'id_error_\' + escapedName;
2387 errorSpan.className = "error";
2388 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2389 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2390 document.getElementById(errorSpan.id).focus();
2393 while (errorSpan.firstChild) {
2394 errorSpan.removeChild(errorSpan.firstChild);
2397 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2399 if (div.className.substr(div.className.length - 6, 6) != " error"
2400 && div.className != "error") {
2401 div.className += " error";
2402 linebreak = document.createElement("br");
2403 linebreak.className = "error";
2404 linebreak.id = \'id_error_break_\' + escapedName;
2405 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2410 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2412 errorSpan.parentNode.removeChild(errorSpan);
2414 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2416 linebreak.parentNode.removeChild(linebreak);
2419 if (div.className.substr(div.className.length - 6, 6) == " error") {
2420 div.className = div.className.substr(0, div.className.length - 6);
2421 } else if (div.className == "error") {
2431 foreach ($test as $elementName => $jsandelement) {
2432 // Fix for bug displaying errors for elements in a group
2434 list($jsArr,$element)=$jsandelement;
2436 $escapedElementName = preg_replace_callback(
2438 function($matches) {
2439 return sprintf("_%2x", ord($matches[0]));
2442 $valFunc = 'validate_' . $this->_formName
. '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2444 if (!is_array($element)) {
2445 $element = [$element];
2447 foreach ($element as $elem) {
2448 if (key_exists('id', $elem->_attributes
)) {
2450 function validate_' . $this->_formName
. '_' . $escapedElementName . '(element, escapedName) {
2451 if (undefined == element) {
2452 //required element was not found, then let form be submitted without client side validation
2456 var errFlag = new Array();
2459 var frm = element.parentNode;
2460 if ((undefined != element.name) && (frm != undefined)) {
2461 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2462 frm = frm.parentNode;
2464 ' . join("\n", $jsArr) . '
2465 return qf_errorHandler(element, _qfMsg, escapedName);
2467 //element name should be defined else error msg will not be displayed.
2472 document.getElementById(\'' . $elem->_attributes
['id'] . '\').addEventListener(\'blur\', function(ev) {
2475 document.getElementById(\'' . $elem->_attributes
['id'] . '\').addEventListener(\'change\', function(ev) {
2481 // This handles both randomised (MDL-65217) and non-randomised IDs.
2482 $errorid = preg_replace('/^id_/', 'id_error_', $this->_attributes
['id']);
2484 ret = validate_' . $this->_formName
. '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2485 if (!ret && !first_focus) {
2487 Y.use(\'moodle-core-event\', function() {
2488 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes
['id'] . '\',
2489 elementid: \'' . $errorid. '\'});
2490 document.getElementById(\'' . $errorid . '\').focus();
2495 // Fix for bug displaying errors for elements in a group
2497 //$element =& $this->getElement($elementName);
2499 //$onBlur = $element->getAttribute('onBlur');
2500 //$onChange = $element->getAttribute('onChange');
2501 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2502 //'onChange' => $onChange . $valFunc));
2504 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2507 function validate_' . $this->_formName
. '() {
2508 if (skipClientValidation) {
2513 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
2514 var first_focus = false;
2515 ' . $validateJS . ';
2519 var form = $(document.getElementById(\'' . $this->_attributes
['id'] . '\')).closest(\'form\');
2520 form.on(M.core.event.FORM_SUBMIT_AJAX, function() {
2522 var myValidator = validate_' . $this->_formName
. ';
2531 document.getElementById(\'' . $this->_attributes
['id'] . '\').addEventListener(\'submit\', function(ev) {
2533 var myValidator = validate_' . $this->_formName
. ';
2537 if (typeof window.tinyMCE !== \'undefined\') {
2538 window.tinyMCE.triggerSave();
2540 if (!myValidator()) {
2541 ev.preventDefault();
2548 $PAGE->requires
->js_amd_inline($js);
2550 // Global variable used to skip the client validation.
2551 return html_writer
::tag('script', 'var skipClientValidation = false;');
2552 } // end func getValidationScript
2555 * Sets default error message
2557 function _setDefaultRuleMessages(){
2558 foreach ($this->_rules
as $field => $rulesarr){
2559 foreach ($rulesarr as $key => $rule){
2560 if ($rule['message']===null){
2562 $a->format
=$rule['format'];
2563 $str=get_string('err_'.$rule['type'], 'form', $a);
2564 if (strpos($str, '[[')!==0){
2565 $this->_rules
[$field][$key]['message']=$str;
2573 * Get list of attributes which have dependencies
2577 function getLockOptionObject(){
2579 foreach ($this->_dependencies
as $dependentOn => $conditions){
2580 $result[$dependentOn] = array();
2581 foreach ($conditions as $condition=>$values) {
2582 $result[$dependentOn][$condition] = array();
2583 foreach ($values as $value=>$dependents) {
2584 $result[$dependentOn][$condition][$value][self
::DEP_DISABLE
] = array();
2585 foreach ($dependents as $dependent) {
2586 $elements = $this->_getElNamesRecursive($dependent);
2587 if (empty($elements)) {
2588 // probably element inside of some group
2589 $elements = array($dependent);
2591 foreach($elements as $element) {
2592 if ($element == $dependentOn) {
2595 $result[$dependentOn][$condition][$value][self
::DEP_DISABLE
][] = $element;
2601 foreach ($this->_hideifs
as $dependenton => $conditions) {
2602 if (!isset($result[$dependenton])) {
2603 $result[$dependenton] = array();
2605 foreach ($conditions as $condition => $values) {
2606 if (!isset($result[$dependenton][$condition])) {
2607 $result[$dependenton][$condition] = array();
2609 foreach ($values as $value => $dependents) {
2610 $result[$dependenton][$condition][$value][self
::DEP_HIDE
] = array();
2611 foreach ($dependents as $dependent) {
2612 $elements = $this->_getElNamesRecursive($dependent);
2613 if (!in_array($dependent, $elements)) {
2614 // Always want to hide the main element, even if it contains sub-elements as well.
2615 $elements[] = $dependent;
2617 foreach ($elements as $element) {
2618 if ($element == $dependenton) {
2621 $result[$dependenton][$condition][$value][self
::DEP_HIDE
][] = $element;
2627 return array($this->getAttribute('id'), $result);
2631 * Get names of element or elements in a group.
2633 * @param HTML_QuickForm_group|element $element element group or element object
2636 function _getElNamesRecursive($element) {
2637 if (is_string($element)) {
2638 if (!$this->elementExists($element)) {
2641 $element = $this->getElement($element);
2644 if (is_a($element, 'HTML_QuickForm_group')) {
2645 $elsInGroup = $element->getElements();
2647 foreach ($elsInGroup as $elInGroup){
2648 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2649 // Groups nested in groups: append the group name to the element and then change it back.
2650 // We will be appending group name again in MoodleQuickForm_group::export_for_template().
2651 $oldname = $elInGroup->getName();
2652 if ($element->_appendName
) {
2653 $elInGroup->setName($element->getName() . '[' . $oldname . ']');
2655 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2656 $elInGroup->setName($oldname);
2658 $elNames[] = $element->getElementName($elInGroup->getName());
2662 } else if (is_a($element, 'HTML_QuickForm_header')) {
2665 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2668 } else if (method_exists($element, 'getPrivateName') &&
2669 !($element instanceof HTML_QuickForm_advcheckbox
)) {
2670 // The advcheckbox element implements a method called getPrivateName,
2671 // but in a way that is not compatible with the generic API, so we
2672 // have to explicitly exclude it.
2673 return array($element->getPrivateName());
2676 $elNames = array($element->getName());
2683 * Adds a dependency for $elementName which will be disabled if $condition is met.
2684 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2685 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2686 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2687 * of the $dependentOn element is $condition (such as equal) to $value.
2689 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2690 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2691 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2693 * @param string $elementName the name of the element which will be disabled
2694 * @param string $dependentOn the name of the element whose state will be checked for condition
2695 * @param string $condition the condition to check
2696 * @param mixed $value used in conjunction with condition.
2698 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2699 // Multiple selects allow for a multiple selection, we transform the array to string here as
2700 // an array cannot be used as a key in an associative array.
2701 if (is_array($value)) {
2702 $value = implode('|', $value);
2704 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
2705 $this->_dependencies
[$dependentOn] = array();
2707 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
2708 $this->_dependencies
[$dependentOn][$condition] = array();
2710 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
2711 $this->_dependencies
[$dependentOn][$condition][$value] = array();
2713 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
2717 * Adds a dependency for $elementName which will be hidden if $condition is met.
2718 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2719 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2720 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2721 * of the $dependentOn element is $condition (such as equal) to $value.
2723 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2724 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2725 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2727 * @param string $elementname the name of the element which will be hidden
2728 * @param string $dependenton the name of the element whose state will be checked for condition
2729 * @param string $condition the condition to check
2730 * @param mixed $value used in conjunction with condition.
2732 public function hideIf($elementname, $dependenton, $condition = 'notchecked', $value = '1') {
2733 // Multiple selects allow for a multiple selection, we transform the array to string here as
2734 // an array cannot be used as a key in an associative array.
2735 if (is_array($value)) {
2736 $value = implode('|', $value);
2738 if (!array_key_exists($dependenton, $this->_hideifs
)) {
2739 $this->_hideifs
[$dependenton] = array();
2741 if (!array_key_exists($condition, $this->_hideifs
[$dependenton])) {
2742 $this->_hideifs
[$dependenton][$condition] = array();
2744 if (!array_key_exists($value, $this->_hideifs
[$dependenton][$condition])) {
2745 $this->_hideifs
[$dependenton][$condition][$value] = array();
2747 $this->_hideifs
[$dependenton][$condition][$value][] = $elementname;
2751 * Registers button as no submit button
2753 * @param string $buttonname name of the button
2755 function registerNoSubmitButton($buttonname){
2756 $this->_noSubmitButtons
[]=$buttonname;
2760 * Checks if button is a no submit button, i.e it doesn't submit form
2762 * @param string $buttonname name of the button to check
2765 function isNoSubmitButton($buttonname){
2766 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
2770 * Registers a button as cancel button
2772 * @param string $addfieldsname name of the button
2774 function _registerCancelButton($addfieldsname){
2775 $this->_cancelButtons
[]=$addfieldsname;
2779 * Displays elements without HTML input tags.
2780 * This method is different to freeze() in that it makes sure no hidden
2781 * elements are included in the form.
2782 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2784 * This function also removes all previously defined rules.
2786 * @param string|array $elementList array or string of element(s) to be frozen
2787 * @return object|bool if element list is not empty then return error object, else true
2789 function hardFreeze($elementList=null)
2791 if (!isset($elementList)) {
2792 $this->_freezeAll
= true;
2793 $elementList = array();
2795 if (!is_array($elementList)) {
2796 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2798 $elementList = array_flip($elementList);
2801 foreach (array_keys($this->_elements
) as $key) {
2802 $name = $this->_elements
[$key]->getName();
2803 if ($this->_freezeAll ||
isset($elementList[$name])) {
2804 $this->_elements
[$key]->freeze();
2805 $this->_elements
[$key]->setPersistantFreeze(false);
2806 unset($elementList[$name]);
2809 $this->_rules
[$name] = array();
2810 // if field is required, remove the rule
2811 $unset = array_search($name, $this->_required
);
2812 if ($unset !== false) {
2813 unset($this->_required
[$unset]);
2818 if (!empty($elementList)) {
2819 return self
::raiseError(null, QUICKFORM_NONEXIST_ELEMENT
, null, E_USER_WARNING
, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
2825 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2827 * This function also removes all previously defined rules of elements it freezes.
2829 * @throws HTML_QuickForm_Error
2830 * @param array $elementList array or string of element(s) not to be frozen
2831 * @return bool returns true
2833 function hardFreezeAllVisibleExcept($elementList)
2835 $elementList = array_flip($elementList);
2836 foreach (array_keys($this->_elements
) as $key) {
2837 $name = $this->_elements
[$key]->getName();
2838 $type = $this->_elements
[$key]->getType();
2840 if ($type == 'hidden'){
2841 // leave hidden types as they are
2842 } elseif (!isset($elementList[$name])) {
2843 $this->_elements
[$key]->freeze();
2844 $this->_elements
[$key]->setPersistantFreeze(false);
2847 $this->_rules
[$name] = array();
2848 // if field is required, remove the rule
2849 $unset = array_search($name, $this->_required
);
2850 if ($unset !== false) {
2851 unset($this->_required
[$unset]);
2859 * Tells whether the form was already submitted
2861 * This is useful since the _submitFiles and _submitValues arrays
2862 * may be completely empty after the trackSubmit value is removed.
2866 function isSubmitted()
2868 return parent
::isSubmitted() && (!$this->isFrozen());
2873 * MoodleQuickForm renderer
2875 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2876 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2878 * Stylesheet is part of standard theme and should be automatically included.
2880 * @package core_form
2881 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2884 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
2886 /** @var array Element template array */
2887 var $_elementTemplates;
2890 * Template used when opening a hidden fieldset
2891 * (i.e. a fieldset that is opened when there is no header element)
2894 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2896 /** @var string Header Template string */
2897 var $_headerTemplate =
2898 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2900 /** @var string Template used when opening a fieldset */
2901 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2903 /** @var string Template used when closing a fieldset */
2904 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2906 /** @var string Required Note template string */
2907 var $_requiredNoteTemplate =
2908 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2911 * Collapsible buttons string template.
2913 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2914 * until the Javascript has been fully loaded.
2918 var $_collapseButtonsTemplate =
2919 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2922 * Array whose keys are element names. If the key exists this is a advanced element
2926 var $_advancedElements = array();
2929 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2933 var $_collapsibleElements = array();
2936 * @var string Contains the collapsible buttons to add to the form.
2938 var $_collapseButtons = '';
2943 public function __construct() {
2944 // switch next two lines for ol li containers for form items.
2945 // $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 --> {typeclass}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
2946 $this->_elementTemplates
= array(
2947 'default' => "\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel} {class}" {aria-live} {groupname}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {typeclass}<!-- BEGIN error --> error<!-- END error -->" data-fieldtype="{type}"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2949 'actionbuttons' => "\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{typeclass} {class}" {groupname}><div class="felement {typeclass}" data-fieldtype="{type}">{element}</div></div>',
2951 'fieldset' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {class}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel}" {groupname}><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {typeclass}<!-- BEGIN error --> error<!-- END error -->" data-fieldtype="{type}"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2953 'static' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}" {groupname}><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->" data-fieldtype="static"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2955 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
2959 parent
::__construct();
2963 * Old syntax of class constructor. Deprecated in PHP7.
2965 * @deprecated since Moodle 3.1
2967 public function MoodleQuickForm_Renderer() {
2968 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2969 self
::__construct();
2973 * Set element's as adavance element
2975 * @param array $elements form elements which needs to be grouped as advance elements.
2977 function setAdvancedElements($elements){
2978 $this->_advancedElements
= $elements;
2982 * Setting collapsible elements
2984 * @param array $elements
2986 function setCollapsibleElements($elements) {
2987 $this->_collapsibleElements
= $elements;
2991 * What to do when starting the form
2993 * @param MoodleQuickForm $form reference of the form
2995 function startForm(&$form){
2997 $this->_reqHTML
= $form->getReqHTML();
2998 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
2999 $this->_advancedHTML
= $form->getAdvancedHTML();
3000 $this->_collapseButtons
= '';
3001 $formid = $form->getAttribute('id');
3002 parent
::startForm($form);
3003 if ($form->isFrozen()){
3004 $this->_formTemplate
= "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
3006 $this->_formTemplate
= "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
3007 $this->_hiddenHtml
.= $form->_pageparams
;
3010 if ($form->is_form_change_checker_enabled()) {
3011 $PAGE->requires
->yui_module('moodle-core-formchangechecker',
3012 'M.core_formchangechecker.init',
3014 'formid' => $formid,
3015 'initialdirtystate' => $form->is_dirty(),
3018 $PAGE->requires
->string_for_js('changesmadereallygoaway', 'moodle');
3020 if (!empty($this->_collapsibleElements
)) {
3021 if (count($this->_collapsibleElements
) > 1) {
3022 $this->_collapseButtons
= $this->_collapseButtonsTemplate
;
3023 $this->_collapseButtons
= str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons
);
3024 $PAGE->requires
->strings_for_js(array('collapseall', 'expandall'), 'moodle');
3026 $PAGE->requires
->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
3028 if (!empty($this->_advancedElements
)){
3029 $PAGE->requires
->js_call_amd('core_form/showadvanced', 'init', [$formid]);
3034 * Create advance group of elements
3036 * @param MoodleQuickForm_group $group Passed by reference
3037 * @param bool $required if input is required field
3038 * @param string $error error message to display
3040 function startGroup(&$group, $required, $error){
3043 // Make sure the element has an id.
3044 $group->_generateId();
3046 // Prepend 'fgroup_' to the ID we generated.
3047 $groupid = 'fgroup_' . $group->getAttribute('id');
3050 $group->updateAttributes(array('id' => $groupid));
3051 $advanced = isset($this->_advancedElements
[$group->getName()]);
3053 $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
3054 $fromtemplate = !empty($html);
3055 if (!$fromtemplate) {
3056 if (method_exists($group, 'getElementTemplateType')) {
3057 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
3059 $html = $this->_elementTemplates
['default'];
3062 if (isset($this->_advancedElements
[$group->getName()])) {
3063 $html = str_replace(' {advanced}', ' advanced', $html);
3064 $html = str_replace('{advancedimg}', $this->_advancedHTML
, $html);
3066 $html = str_replace(' {advanced}', '', $html);
3067 $html = str_replace('{advancedimg}', '', $html);
3069 if (method_exists($group, 'getHelpButton')) {
3070 $html = str_replace('{help}', $group->getHelpButton(), $html);
3072 $html = str_replace('{help}', '', $html);
3074 $html = str_replace('{id}', $group->getAttribute('id'), $html);
3075 $html = str_replace('{name}', $group->getName(), $html);
3076 $html = str_replace('{groupname}', 'data-groupname="'.$group->getName().'"', $html);
3077 $html = str_replace('{typeclass}', 'fgroup', $html);
3078 $html = str_replace('{type}', 'group', $html);
3079 $html = str_replace('{class}', $group->getAttribute('class'), $html);
3081 if ($group->getLabel() == '') {
3082 $emptylabel = 'femptylabel';
3084 $html = str_replace('{emptylabel}', $emptylabel, $html);
3086 $this->_templates
[$group->getName()] = $html;
3087 // Fix for bug in tableless quickforms that didn't allow you to stop a
3088 // fieldset before a group of elements.
3089 // if the element name indicates the end of a fieldset, close the fieldset
3090 if (in_array($group->getName(), $this->_stopFieldsetElements
) && $this->_fieldsetsOpen
> 0) {
3091 $this->_html
.= $this->_closeFieldsetTemplate
;
3092 $this->_fieldsetsOpen
--;
3094 if (!$fromtemplate) {
3095 parent
::startGroup($group, $required, $error);
3097 $this->_html
.= $html;
3104 * @param HTML_QuickForm_element $element element
3105 * @param bool $required if input is required field
3106 * @param string $error error message to display
3108 function renderElement(&$element, $required, $error){
3111 // Make sure the element has an id.
3112 $element->_generateId();
3113 $advanced = isset($this->_advancedElements
[$element->getName()]);
3115 $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
3116 $fromtemplate = !empty($html);
3117 if (!$fromtemplate) {
3118 // Adding stuff to place holders in template
3119 // check if this is a group element first.
3120 if (($this->_inGroup
) and !empty($this->_groupElementTemplate
)) {
3121 // So it gets substitutions for *each* element.
3122 $html = $this->_groupElementTemplate
;
3123 } else if (method_exists($element, 'getElementTemplateType')) {
3124 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
3126 $html = $this->_elementTemplates
['default'];
3128 if (isset($this->_advancedElements
[$element->getName()])) {
3129 $html = str_replace(' {advanced}', ' advanced', $html);
3130 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
3132 $html = str_replace(' {advanced}', '', $html);
3133 $html = str_replace(' {aria-live}', '', $html);
3135 if (isset($this->_advancedElements
[$element->getName()]) ||
$element->getName() == 'mform_showadvanced') {
3136 $html = str_replace('{advancedimg}', $this->_advancedHTML
, $html);
3138 $html = str_replace('{advancedimg}', '', $html);
3140 $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
3141 $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
3142 $html = str_replace('{type}', $element->getType(), $html);
3143 $html = str_replace('{name}', $element->getName(), $html);
3144 $html = str_replace('{groupname}', '', $html);
3145 $html = str_replace('{class}', $element->getAttribute('class'), $html);
3147 if ($element->getLabel() == '') {
3148 $emptylabel = 'femptylabel';
3150 $html = str_replace('{emptylabel}', $emptylabel, $html);
3151 if (method_exists($element, 'getHelpButton')) {
3152 $html = str_replace('{help}', $element->getHelpButton(), $html);
3154 $html = str_replace('{help}', '', $html);
3157 if ($this->_inGroup
) {
3158 $this->_groupElementTemplate
= $html;
3161 if (($this->_inGroup
) and !empty($this->_groupElementTemplate
)) {
3162 $this->_groupElementTemplate
= $html;
3163 } else if (!isset($this->_templates
[$element->getName()])) {
3164 $this->_templates
[$element->getName()] = $html;
3167 if (!$fromtemplate) {
3168 parent
::renderElement($element, $required, $error);
3170 if (in_array($element->getName(), $this->_stopFieldsetElements
) && $this->_fieldsetsOpen
> 0) {
3171 $this->_html
.= $this->_closeFieldsetTemplate
;
3172 $this->_fieldsetsOpen
--;
3174 $this->_html
.= $html;
3179 * Called when visiting a form, after processing all form elements
3180 * Adds required note, form attributes, validation javascript and form content.
3182 * @global moodle_page $PAGE
3183 * @param moodleform $form Passed by reference
3185 function finishForm(&$form){
3187 if ($form->isFrozen()){
3188 $this->_hiddenHtml
= '';
3190 parent
::finishForm($form);
3191 $this->_html
= str_replace('{collapsebtns}', $this->_collapseButtons
, $this->_html
);
3192 if (!$form->isFrozen()) {
3193 $args = $form->getLockOptionObject();
3194 if (count($args[1]) > 0) {
3195 $PAGE->requires
->js_init_call('M.form.initFormDependencies', $args, true, moodleform
::get_js_module());
3200 * Called when visiting a header element
3202 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
3203 * @global moodle_page $PAGE
3205 function renderHeader(&$header) {
3208 $header->_generateId();
3209 $name = $header->getName();
3211 $id = empty($name) ?
'' : ' id="' . $header->getAttribute('id') . '"';
3212 if (is_null($header->_text
)) {
3214 } elseif (!empty($name) && isset($this->_templates
[$name])) {
3215 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
3217 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
3220 if ($this->_fieldsetsOpen
> 0) {
3221 $this->_html
.= $this->_closeFieldsetTemplate
;
3222 $this->_fieldsetsOpen
--;
3225 // Define collapsible classes for fieldsets.
3227 $fieldsetclasses = array('clearfix');
3228 if (isset($this->_collapsibleElements
[$header->getName()])) {
3229 $fieldsetclasses[] = 'collapsible';
3230 if ($this->_collapsibleElements
[$header->getName()]) {
3231 $fieldsetclasses[] = 'collapsed';
3235 if (isset($this->_advancedElements
[$name])){
3236 $fieldsetclasses[] = 'containsadvancedelements';
3239 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
3240 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
3242 $this->_html
.= $openFieldsetTemplate . $header_html;
3243 $this->_fieldsetsOpen++
;
3247 * Return Array of element names that indicate the end of a fieldset
3251 function getStopFieldsetElements(){
3252 return $this->_stopFieldsetElements
;
3257 * Required elements validation
3259 * This class overrides QuickForm validation since it allowed space or empty tag as a value
3261 * @package core_form
3263 * @copyright 2006 Jamie Pratt <me@jamiep.org>
3264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3266 class MoodleQuickForm_Rule_Required
extends HTML_QuickForm_Rule
{
3268 * Checks if an element is not empty.
3269 * This is a server-side validation, it works for both text fields and editor fields
3271 * @param string $value Value to check
3272 * @param int|string|array $options Not used yet
3273 * @return bool true if value is not empty
3275 function validate($value, $options = null) {
3277 if (is_array($value) && array_key_exists('text', $value)) {
3278 $value = $value['text'];
3280 if (is_array($value)) {
3281 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
3282 $value = implode('', $value);
3284 $stripvalues = array(
3285 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
3286 '#(\xc2\xa0|\s| )#', // Any whitespaces actually.
3288 if (!empty($CFG->strictformsrequired
)) {
3289 $value = preg_replace($stripvalues, '', (string)$value);
3291 if ((string)$value == '') {
3298 * This function returns Javascript code used to build client-side validation.
3299 * It checks if an element is not empty.
3301 * @param int $format format of data which needs to be validated.
3304 function getValidationScript($format = null) {
3306 if (!empty($CFG->strictformsrequired
)) {
3307 if (!empty($format) && $format == FORMAT_HTML
) {
3308 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)| |\s+/ig, '') == ''");
3310 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
3313 return array('', "{jsVar} == ''");
3319 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
3320 * @name $_HTML_QuickForm_default_renderer
3322 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
3324 /** Please keep this list in alphabetical order. */
3325 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
3326 MoodleQuickForm
::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
3327 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
3328 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3329 MoodleQuickForm
::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
3330 MoodleQuickForm
::registerElementType('cohort', "$CFG->libdir/form/cohort.php", 'MoodleQuickForm_cohort');
3331 MoodleQuickForm
::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3332 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3333 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3334 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3335 MoodleQuickForm
::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3336 MoodleQuickForm
::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3337 MoodleQuickForm
::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3338 MoodleQuickForm
::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3339 MoodleQuickForm
::registerElementType('filetypes', "$CFG->libdir/form/filetypes.php", 'MoodleQuickForm_filetypes');
3340 MoodleQuickForm
::registerElementType('float', "$CFG->libdir/form/float.php", 'MoodleQuickForm_float');
3341 MoodleQuickForm
::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3342 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3343 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3344 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3345 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
3346 MoodleQuickForm
::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3347 MoodleQuickForm
::registerElementType('defaultcustom', "$CFG->libdir/form/defaultcustom.php", 'MoodleQuickForm_defaultcustom');
3348 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3349 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3350 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3351 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3352 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3353 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3354 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3355 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3356 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3357 MoodleQuickForm
::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3358 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3359 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3360 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3361 MoodleQuickForm
::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3362 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3363 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3364 MoodleQuickForm
::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3365 MoodleQuickForm
::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3367 MoodleQuickForm
::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");