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/>.
17 defined('MOODLE_INTERNAL') ||
die;
19 require_once($CFG->libdir
.'/formslib.php');
20 require_once($CFG->libdir
.'/gradelib.php');
21 require_once($CFG->libdir
.'/plagiarismlib.php');
23 use core_grades\component_gradeitems
;
26 * This class adds extra methods to form wrapper specific to be used for module add / update forms
27 * mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html Moodleform.
29 * @package core_course
30 * @copyright Andrew Nicols <andrew@nicols.co.uk>
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 abstract class moodleform_mod
extends moodleform
{
35 use \core_completion\form\form_trait
;
40 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
41 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
48 * Section of course that module instance will be put in or is in.
49 * This is always the section number itself (column 'section' from 'course_sections' table).
55 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
70 * List of modform features
74 * @var array Custom completion-rule elements, if enabled
76 protected $_customcompletionelements;
78 * @var string name of module.
81 /** current context, course or module depends if already exists*/
84 /** a flag indicating whether outcomes are being used*/
85 protected $_outcomesused;
88 * @var bool A flag used to indicate that this module should lock settings
89 * based on admin settings flags in definition_after_data.
91 protected $applyadminlockedflags = false;
93 /** @var object The course format of the current course. */
94 protected $courseformat;
96 /** @var string Whether this is graded or rated. */
97 private $gradedorrated = null;
99 public function __construct($current, $section, $cm, $course) {
102 $this->current
= $current;
103 $this->_instance
= $current->instance
;
104 $this->_section
= $section;
106 $this->_course
= $course;
108 $this->context
= context_module
::instance($this->_cm
->id
);
110 $this->context
= context_course
::instance($course->id
);
113 // Set the course format.
114 require_once($CFG->dirroot
. '/course/format/lib.php');
115 $this->courseformat
= course_get_format($course);
117 // Guess module name if not set.
118 if (is_null($this->_modname
)) {
120 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
121 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
122 throw new \
moodle_exception('unknownmodulename');
124 $this->_modname
= $matches[1];
126 $this->init_features();
127 parent
::__construct('modedit.php');
131 * Old syntax of class constructor. Deprecated in PHP7.
133 * @deprecated since Moodle 3.1
135 public function moodleform_mod($current, $section, $cm, $course) {
136 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
137 self
::__construct($current, $section, $cm, $course);
141 * Get the current data for the form.
142 * @return stdClass|null
144 public function get_current() {
145 return $this->current
;
149 * Get the DB record for the current instance.
150 * @return stdClass|null
152 public function get_instance() {
153 return $this->_instance
;
157 * Get the course section number (relative).
160 public function get_section() {
161 return $this->_section
;
168 public function get_course() {
169 return $this->_course
;
173 * Get the course module object.
174 * @return stdClass|null
176 public function get_coursemodule() {
181 * Return the course context for new modules, or the module context for existing modules.
184 public function get_context() {
185 return $this->context
;
189 * Return the features this module supports.
192 public function get_features() {
193 return $this->_features
;
196 protected function init_features() {
199 $this->_features
= new stdClass();
200 $this->_features
->groups
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPS
, false);
201 $this->_features
->groupings
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPINGS
, false);
202 $this->_features
->outcomes
= (!empty($CFG->enableoutcomes
) and plugin_supports('mod', $this->_modname
, FEATURE_GRADE_OUTCOMES
, true));
203 $this->_features
->hasgrades
= plugin_supports('mod', $this->_modname
, FEATURE_GRADE_HAS_GRADE
, false);
204 $this->_features
->idnumber
= plugin_supports('mod', $this->_modname
, FEATURE_IDNUMBER
, true);
205 $this->_features
->introeditor
= plugin_supports('mod', $this->_modname
, FEATURE_MOD_INTRO
, true);
206 $this->_features
->defaultcompletion
= plugin_supports('mod', $this->_modname
, FEATURE_MODEDIT_DEFAULT_COMPLETION
, true);
207 $this->_features
->rating
= plugin_supports('mod', $this->_modname
, FEATURE_RATE
, false);
208 $this->_features
->showdescription
= plugin_supports('mod', $this->_modname
, FEATURE_SHOW_DESCRIPTION
, false);
209 $this->_features
->gradecat
= ($this->_features
->outcomes
or $this->_features
->hasgrades
);
210 $this->_features
->advancedgrading
= plugin_supports('mod', $this->_modname
, FEATURE_ADVANCED_GRADING
, false);
211 $this->_features
->hasnoview
= plugin_supports('mod', $this->_modname
, FEATURE_NO_VIEW_LINK
, false);
212 $this->_features
->canrescale
= (component_callback_exists('mod_' . $this->_modname
, 'rescale_activity_grades') !== false);
216 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
217 * This method is also called in the bulk activity completion form.
219 * Only available on moodleform_mod.
221 * @param array $default_values passed by reference
223 function data_preprocessing(&$default_values){
224 if (empty($default_values['scale'])) {
225 $default_values['assessed'] = 0;
228 if (empty($default_values['assessed'])){
229 $default_values['ratingtime'] = 0;
231 $default_values['ratingtime']=
232 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ?
1 : 0;
237 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
239 function definition_after_data() {
240 global $CFG, $COURSE;
241 $mform =& $this->_form
;
243 if ($id = $mform->getElementValue('update')) {
244 $modulename = $mform->getElementValue('modulename');
245 $instance = $mform->getElementValue('instance');
246 $component = "mod_{$modulename}";
248 if ($this->_features
->gradecat
) {
249 $hasgradeitems = false;
250 $items = grade_item
::fetch_all([
252 'itemmodule' => $modulename,
253 'iteminstance' => $instance,
254 'courseid' => $COURSE->id
,
257 $gradecategories = [];
258 $removecategories = [];
259 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
260 if (!empty($items)) {
261 foreach ($items as $item) {
262 if (!empty($item->outcomeid
)) {
263 $elname = 'outcome_'.$item->outcomeid
;
264 if ($mform->elementExists($elname)) {
265 $mform->hardFreeze($elname); // prevent removing of existing outcomes
268 $hasgradeitems = true;
272 foreach ($items as $item) {
273 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber(
279 if (!isset($gradecategories[$gradecatfieldname])) {
280 $gradecategories[$gradecatfieldname] = $item->categoryid
;
281 } else if ($gradecategories[$gradecatfieldname] != $item->categoryid
) {
282 $removecategories[$gradecatfieldname] = true;
287 foreach ($removecategories as $toremove) {
288 if ($mform->elementExists($toremove)) {
289 $mform->removeElement($toremove);
295 if ($COURSE->groupmodeforce
) {
296 if ($mform->elementExists('groupmode')) {
297 // The groupmode can not be changed if forced from course settings.
298 $mform->hardFreeze('groupmode');
302 // Don't disable/remove groupingid if it is currently set to something, otherwise you cannot turn it off at same
303 // time as turning off other option (MDL-30764).
304 if (empty($this->_cm
) ||
!$this->_cm
->groupingid
) {
305 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce
)) {
306 $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS
);
308 } else if (!$mform->elementExists('groupmode')) {
309 // Groupings have no use without groupmode.
310 if ($mform->elementExists('groupingid')) {
311 $mform->removeElement('groupingid');
313 // Nor does the group restrictions button.
314 if ($mform->elementExists('restrictgroupbutton')) {
315 $mform->removeElement('restrictgroupbutton');
320 // Completion: If necessary, freeze fields.
321 $this->definition_after_data_completion();
323 // Freeze admin defaults if required (and not different from default)
324 $this->apply_admin_locked_flags();
326 $this->plugin_extend_coursemodule_definition_after_data();
330 function validation($data, $files) {
331 global $COURSE, $DB, $CFG;
333 $mform =& $this->_form
;
335 $errors = parent
::validation($data, $files);
337 if ($mform->elementExists('name')) {
338 $name = trim($data['name']);
340 $errors['name'] = get_string('required');
344 $grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
345 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id
));
346 if ($data['coursemodule']) {
347 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
352 if ($mform->elementExists('cmidnumber')) {
353 // verify the idnumber
354 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id
, $grade_item, $cm)) {
355 $errors['cmidnumber'] = get_string('idnumbertaken');
359 $component = "mod_{$this->_modname}";
360 $itemnames = component_gradeitems
::get_itemname_mapping_for_component($component);
361 foreach ($itemnames as $itemnumber => $itemname) {
362 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
363 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
364 $assessedfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
365 $scalefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
367 // Ratings: Don't let them select an aggregate type without selecting a scale.
368 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
369 // invalid. If ratings have been selected then the user must select either a scale or max points.
370 // This matches (horrible) logic in data_preprocessing.
371 if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
372 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
375 // Check that the grade pass is a valid number.
376 $gradepassvalid = false;
377 if (isset($data[$gradepassfieldname])) {
378 if (unformat_float($data[$gradepassfieldname], true) === false) {
379 $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
381 $gradepassvalid = true;
385 // Grade to pass: ensure that the grade to pass is valid for points and scales.
386 // If we are working with a scale, convert into a positive number for validation.
387 if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) ||
!empty($data[$scalefieldname]))) {
388 $scale = !empty($data[$gradefieldname]) ?
$data[$gradefieldname] : $data[$scalefieldname];
390 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
391 $grade = count(explode(',', $scalevalues->scale
));
395 if (unformat_float($data[$gradepassfieldname]) > $grade) {
396 $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
400 // We have a grade if there is a non-falsey value for:
401 // - the assessedfieldname for Ratings there; or
402 // - the gradefieldname for Ratings there.
403 if (empty($data[$assessedfieldname]) && empty($data[$gradefieldname])) {
404 // There are no grades set therefore completion is not allowed.
405 if (isset($data['completiongradeitemnumber']) && $data['completiongradeitemnumber'] == (string) $itemnumber) {
406 $errors['completiongradeitemnumber'] = get_string(
407 'badcompletiongradeitemnumber',
409 get_string("grade_{$itemname}_name", $component)
414 if (isset($data['completionpassgrade']) && $data['completionpassgrade']) {
415 // We need to check whether there's a valid gradepass value.
416 // This can either be in completiongradeitemnumber when there are multiple options OR,
417 // The first grade item if completionusegrade is specified.
418 $validategradepass = false;
419 if (isset($data['completiongradeitemnumber'])) {
420 if ($data['completiongradeitemnumber'] == (string)$itemnumber) {
421 $validategradepass = true;
423 } else if (isset($data['completionusegrade']) && $data['completionusegrade']) {
424 $validategradepass = true;
427 // We need to make all the validations related with $gradepassfieldname
428 // with them being correct floats, keeping the originals unmodified for
429 // later validations / showing the form back...
430 // TODO: Note that once MDL-73994 is fixed we'll have to re-visit this and
431 // adapt the code below to the new values arriving here, without forgetting
432 // the special case of empties and nulls.
433 $gradepass = isset($data[$gradepassfieldname]) ?
unformat_float($data[$gradepassfieldname]) : null;
435 // Confirm gradepass is a valid non-empty (null or zero) value.
436 if ($validategradepass && (is_null($gradepass) ||
$gradepass == 0)) {
437 $errors['completionpassgrade'] = get_string(
438 'activitygradetopassnotset',
445 // Completion: Check completion fields don't have errors.
446 $errors = array_merge($errors, $this->validate_completion($data));
448 // Availability: Check availability field does not have errors.
449 if (!empty($CFG->enableavailability
)) {
450 \core_availability\frontend
::report_validation_errors($data, $errors);
453 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
454 if (!empty($pluginerrors)) {
455 $errors = array_merge($errors, $pluginerrors);
462 * Extend the validation function from any other plugin.
464 * @param stdClass $data The form data.
465 * @return array $errors The list of errors keyed by element name.
467 protected function plugin_extend_coursemodule_validation($data) {
470 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
471 foreach ($callbacks as $type => $plugins) {
472 foreach ($plugins as $plugin => $pluginfunction) {
473 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
474 $pluginerrors = $pluginfunction($this, $data);
475 if (!empty($pluginerrors)) {
476 $errors = array_merge($errors, $pluginerrors);
484 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
485 * form definition (new entry form); this function is used to load in data where values
486 * already exist and data is being edited (edit entry form).
488 * @param mixed $default_values object or array of default values
490 function set_data($default_values) {
491 if (is_object($default_values)) {
492 $default_values = (array)$default_values;
495 $this->data_preprocessing($default_values);
496 parent
::set_data($default_values);
500 * Adds all the standard elements to a form to edit the settings for an activity module.
502 protected function standard_coursemodule_elements() {
503 global $COURSE, $CFG, $DB;
504 $mform =& $this->_form
;
506 $this->_outcomesused
= false;
507 if ($this->_features
->outcomes
) {
508 if ($outcomes = grade_outcome
::fetch_all_available($COURSE->id
)) {
509 $this->_outcomesused
= true;
510 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
511 foreach($outcomes as $outcome) {
512 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id
, $outcome->get_name());
517 if ($this->_features
->rating
) {
518 $this->add_rating_settings($mform, 0);
521 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
523 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section
);
525 !empty($CFG->allowstealth
) &&
526 $this->courseformat
->allow_stealth_module_visibility($this->_cm
, $section) &&
527 !$this->_features
->hasnoview
;
528 if ($allowstealth && $section->visible
) {
529 $modvisiblelabel = 'modvisiblewithstealth';
530 } else if ($section->visible
) {
531 $modvisiblelabel = 'modvisible';
533 $modvisiblelabel = 'modvisiblehiddensection';
535 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
536 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible
, 'cm' => $this->_cm
));
537 $mform->addHelpButton('visible', $modvisiblelabel);
538 if (!empty($this->_cm
) && !has_capability('moodle/course:activityvisibility', $this->get_context())) {
539 $mform->hardFreeze('visible');
542 if ($this->_features
->idnumber
) {
543 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
544 $mform->setType('cmidnumber', PARAM_RAW
);
545 $mform->addHelpButton('cmidnumber', 'idnumbermod');
548 if (has_capability('moodle/course:setforcedlanguage', $this->get_context())) {
549 $languages = ['' => get_string('forceno')];
550 $languages +
= get_string_manager()->get_list_of_translations();
552 $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
555 if ($CFG->downloadcoursecontentallowed
) {
557 DOWNLOAD_COURSE_CONTENT_DISABLED
=> get_string('no'),
558 DOWNLOAD_COURSE_CONTENT_ENABLED
=> get_string('yes'),
560 $mform->addElement('select', 'downloadcontent', get_string('downloadcontent', 'course'), $choices);
561 $downloadcontentdefault = $this->_cm
->downloadcontent ?? DOWNLOAD_COURSE_CONTENT_ENABLED
;
562 $mform->addHelpButton('downloadcontent', 'downloadcontent', 'course');
563 if (has_capability('moodle/course:configuredownloadcontent', $this->get_context())) {
564 $mform->setDefault('downloadcontent', $downloadcontentdefault);
566 $mform->hardFreeze('downloadcontent');
567 $mform->setConstant('downloadcontent', $downloadcontentdefault);
571 if ($this->_features
->groups
) {
572 $options = array(NOGROUPS
=> get_string('groupsnone'),
573 SEPARATEGROUPS
=> get_string('groupsseparate'),
574 VISIBLEGROUPS
=> get_string('groupsvisible'));
575 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS
);
576 $mform->addHelpButton('groupmode', 'groupmode', 'group');
579 if ($this->_features
->groupings
) {
580 // Groupings selector - used to select grouping for groups in activity.
582 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id
))) {
583 foreach ($groupings as $grouping) {
584 $options[$grouping->id
] = format_string($grouping->name
);
587 core_collator
::asort($options);
588 $options = array(0 => get_string('none')) +
$options;
589 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
590 $mform->addHelpButton('groupingid', 'grouping', 'group');
593 if (!empty($CFG->enableavailability
)) {
594 // Add special button to end of previous section if groups/groupings
597 $availabilityplugins = \core\plugininfo\availability
::get_enabled_plugins();
598 $groupavailability = $this->_features
->groups
&& array_key_exists('group', $availabilityplugins);
599 $groupingavailability = $this->_features
->groupings
&& array_key_exists('grouping', $availabilityplugins);
601 if ($groupavailability ||
$groupingavailability) {
602 // When creating the button, we need to set type=button to prevent it behaving as a submit.
603 $mform->addElement('static', 'restrictgroupbutton', '',
604 html_writer
::tag('button', get_string('restrictbygroup', 'availability'), [
605 'id' => 'restrictbygroup',
607 'disabled' => 'disabled',
608 'class' => 'btn btn-secondary',
609 'data-groupavailability' => $groupavailability,
610 'data-groupingavailability' => $groupingavailability
615 // Availability field. This is just a textarea; the user interface
616 // interaction is all implemented in JavaScript.
617 $mform->addElement('header', 'availabilityconditionsheader',
618 get_string('restrictaccess', 'availability'));
619 // Note: This field cannot be named 'availability' because that
620 // conflicts with fields in existing modules (such as assign).
621 // So it uses a long name that will not conflict.
622 $mform->addElement('textarea', 'availabilityconditionsjson',
623 get_string('accessrestrictions', 'availability'),
624 ['class' => 'd-none']
627 // The _cm variable may not be a proper cm_info, so get one from modinfo.
629 $modinfo = get_fast_modinfo($COURSE);
630 $cm = $modinfo->get_cm($this->_cm
->id
);
634 \core_availability\frontend
::include_all_javascript($COURSE, $cm);
637 // Conditional activities: completion tracking section
638 if(!isset($completion)) {
639 $completion = new completion_info($COURSE);
642 // Add the completion tracking elements to the form.
643 if ($completion->is_enabled()) {
644 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
645 $this->add_completion_elements();
648 // Populate module tags.
649 if (core_tag_tag
::is_enabled('core', 'course_modules')) {
650 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
651 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
653 $tags = core_tag_tag
::get_item_tags_array('core', 'course_modules', $this->_cm
->id
);
654 $mform->setDefault('tags', $tags);
658 $this->standard_hidden_coursemodule_elements();
660 $this->plugin_extend_coursemodule_standard_elements();
664 * Add rating settings.
666 * @param moodleform_mod $mform
667 * @param int $itemnumber
669 protected function add_rating_settings($mform, int $itemnumber) {
670 global $CFG, $COURSE;
672 if ($this->gradedorrated
&& $this->gradedorrated
!== 'rated') {
675 $this->gradedorrated
= 'rated';
677 require_once("{$CFG->dirroot}/rating/lib.php");
678 $rm = new rating_manager();
680 $component = "mod_{$this->_modname}";
681 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
682 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
683 $assessedfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
684 $scalefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
686 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
688 $isupdate = !empty($this->_cm
);
690 $rolenamestring = null;
692 $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
693 $rolenames = get_role_names_with_caps_in_context($this->get_context(), $capabilities);
694 $rolenamestring = implode(', ', $rolenames);
696 $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
699 $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
700 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
702 $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
703 $mform->setDefault($assessedfieldname, 0);
704 $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
707 'isupdate' => $isupdate,
708 'currentgrade' => false,
709 'hasgrades' => false,
710 'canrescale' => false,
711 'useratings' => true,
714 $gradeitem = grade_item
::fetch([
716 'itemmodule' => $this->_cm
->modname
,
717 'iteminstance' => $this->_cm
->instance
,
718 'itemnumber' => $itemnumber,
719 'courseid' => $COURSE->id
,
722 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
723 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
724 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
725 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
729 $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
730 $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
731 $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
732 $mform->setDefault($scalefieldname, $CFG->gradepointdefault
);
734 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
735 $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
737 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
738 $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
739 $mform->hideIf('assesstimestart', 'ratingtime');
741 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
742 $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
743 $mform->hideIf('assesstimefinish', 'ratingtime');
745 if ($this->_features
->gradecat
) {
749 get_string('gradecategoryonmodform', 'grades'),
750 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
)
752 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
753 $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
754 $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
758 $mform->addElement('float', $gradepassfieldname, get_string('gradepass', 'grades'));
759 $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
760 $mform->setDefault($gradepassfieldname, '');
761 $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
762 $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
766 * Plugins can extend the coursemodule settings form.
768 protected function plugin_extend_coursemodule_standard_elements() {
769 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
770 foreach ($callbacks as $type => $plugins) {
771 foreach ($plugins as $plugin => $pluginfunction) {
772 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
774 $pluginfunction($this, $this->_form
);
780 * Plugins can extend the coursemodule settings form after the data is set.
782 protected function plugin_extend_coursemodule_definition_after_data() {
783 $callbacks = get_plugins_with_function('coursemodule_definition_after_data', 'lib.php');
784 foreach ($callbacks as $type => $plugins) {
785 foreach ($plugins as $plugin => $pluginfunction) {
786 $pluginfunction($this, $this->_form
);
792 * Can be overridden to add custom completion rules if the module wishes
793 * them. If overriding this, you should also override completion_rule_enabled.
795 * Just add elements to the form as needed and return the list of IDs. The
796 * system will call disabledIf and handle other behaviour for each returned
798 * @return array Array of string IDs of added items, empty array if none
800 function add_completion_rules() {
805 * Called during validation. Override to indicate, based on the data, whether
806 * a custom completion rule is enabled (selected).
808 * @param array $data Input data (not yet validated)
809 * @return bool True if one or more rules is enabled, false if none are;
810 * default returns false
812 function completion_rule_enabled($data) {
816 function standard_hidden_coursemodule_elements(){
817 $mform =& $this->_form
;
818 $mform->addElement('hidden', 'course', 0);
819 $mform->setType('course', PARAM_INT
);
821 $mform->addElement('hidden', 'coursemodule', 0);
822 $mform->setType('coursemodule', PARAM_INT
);
824 $mform->addElement('hidden', 'section', 0);
825 $mform->setType('section', PARAM_INT
);
827 $mform->addElement('hidden', 'module', 0);
828 $mform->setType('module', PARAM_INT
);
830 $mform->addElement('hidden', 'modulename', '');
831 $mform->setType('modulename', PARAM_PLUGIN
);
833 $mform->addElement('hidden', 'instance', 0);
834 $mform->setType('instance', PARAM_INT
);
836 $mform->addElement('hidden', 'add', 0);
837 $mform->setType('add', PARAM_ALPHANUM
);
839 $mform->addElement('hidden', 'update', 0);
840 $mform->setType('update', PARAM_INT
);
842 $mform->addElement('hidden', 'return', 0);
843 $mform->setType('return', PARAM_BOOL
);
845 $mform->addElement('hidden', 'sr', 0);
846 $mform->setType('sr', PARAM_INT
);
848 $mform->addElement('hidden', 'beforemod', 0);
849 $mform->setType('beforemod', PARAM_INT
);
851 $mform->addElement('hidden', 'showonly', '');
852 $mform->setType('showonly', PARAM_ALPHANUMEXT
);
855 public function standard_grading_coursemodule_elements() {
856 global $COURSE, $CFG;
858 if ($this->gradedorrated
&& $this->gradedorrated
!== 'graded') {
861 if ($this->_features
->rating
) {
864 $this->gradedorrated
= 'graded';
867 $component = "mod_{$this->_modname}";
868 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
869 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
870 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
872 $mform =& $this->_form
;
873 $isupdate = !empty($this->_cm
);
874 $gradeoptions = array('isupdate' => $isupdate,
875 'currentgrade' => false,
876 'hasgrades' => false,
877 'canrescale' => $this->_features
->canrescale
,
878 'useratings' => $this->_features
->rating
);
880 if ($this->_features
->hasgrades
) {
881 if ($this->_features
->gradecat
) {
882 $mform->addElement('header', 'modstandardgrade', get_string('gradenoun'));
885 //if supports grades and grades arent being handled via ratings
887 $gradeitem = grade_item
::fetch(array('itemtype' => 'mod',
888 'itemmodule' => $this->_cm
->modname
,
889 'iteminstance' => $this->_cm
->instance
,
891 'courseid' => $COURSE->id
));
893 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
894 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
895 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
896 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
899 $mform->addElement('modgrade', $gradefieldname, get_string('gradenoun'), $gradeoptions);
900 $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
901 $mform->setDefault($gradefieldname, $CFG->gradepointdefault
);
903 if ($this->_features
->advancedgrading
904 and !empty($this->current
->_advancedgradingdata
['methods'])
905 and !empty($this->current
->_advancedgradingdata
['areas'])) {
907 if (count($this->current
->_advancedgradingdata
['areas']) == 1) {
908 // if there is just one gradable area (most cases), display just the selector
909 // without its name to make UI simplier
910 $areadata = reset($this->current
->_advancedgradingdata
['areas']);
911 $areaname = key($this->current
->_advancedgradingdata
['areas']);
912 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
913 get_string('gradingmethod', 'core_grading'), $this->current
->_advancedgradingdata
['methods']);
914 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
915 $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
918 // the module defines multiple gradable areas, display a selector
919 // for each of them together with a name of the area
920 $areasgroup = array();
921 foreach ($this->current
->_advancedgradingdata
['areas'] as $areaname => $areadata) {
922 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
923 $areadata['title'], $this->current
->_advancedgradingdata
['methods']);
924 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
926 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
927 array(' ', '<br />'), false);
931 if ($this->_features
->gradecat
) {
932 $mform->addElement('select', $gradecatfieldname,
933 get_string('gradecategoryonmodform', 'grades'),
934 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
));
935 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
936 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
940 $mform->addElement('float', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
941 $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
942 $mform->setDefault($gradepassfieldname, '');
943 $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
948 * Add an editor for an activity's introduction field.
949 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
950 * @param null $required Override system default for requiremodintro
951 * @param null $customlabel Override default label for editor
952 * @throws coding_exception
954 protected function add_intro_editor($required=null, $customlabel=null) {
955 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
956 debugging($str, DEBUG_DEVELOPER
);
958 $this->standard_intro_elements($customlabel);
963 * Add an editor for an activity's introduction field.
965 * @param null $customlabel Override default label for editor
966 * @throws coding_exception
968 protected function standard_intro_elements($customlabel=null) {
971 $required = $CFG->requiremodintro
;
973 $mform = $this->_form
;
974 $label = is_null($customlabel) ?
get_string('moduleintro') : $customlabel;
976 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES
,
977 'noclean' => true, 'context' => $this->context
, 'subdirs' => true));
978 $mform->setType('introeditor', PARAM_RAW
); // no XSS prevention here, users must be trusted
980 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
983 // If the 'show description' feature is enabled, this checkbox appears below the intro.
984 // We want to hide that when using the singleactivity course format because it is confusing.
985 if ($this->_features
->showdescription
&& $this->courseformat
->has_view_page()) {
986 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
987 $mform->addHelpButton('showdescription', 'showdescription');
992 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
994 * @param bool $cancel show cancel button
995 * @param string $submitlabel null means default, false means none, string is label text
996 * @param string $submit2label null means default, false means none, string is label text
999 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1000 if (is_null($submitlabel)) {
1001 $submitlabel = get_string('savechangesanddisplay');
1004 if (is_null($submit2label)) {
1005 $submit2label = get_string('savechangesandreturntocourse');
1008 $mform = $this->_form
;
1010 $mform->addElement('checkbox', 'coursecontentnotification', get_string('coursecontentnotification', 'course'));
1011 $mform->addHelpButton('coursecontentnotification', 'coursecontentnotification', 'course');
1012 $mform->closeHeaderBefore('coursecontentnotification');
1014 // elements in a row need a group
1015 $buttonarray = array();
1017 // Label for the submit button to return to the course.
1018 // Ignore this button in single activity format because it is confusing.
1019 if ($submit2label !== false && $this->courseformat
->has_view_page()) {
1020 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1023 if ($submitlabel !== false) {
1024 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1028 $buttonarray[] = &$mform->createElement('cancel');
1031 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1032 $mform->setType('buttonar', PARAM_RAW
);
1036 * Get the list of admin settings for this module and apply any locked settings.
1037 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1038 * in that function because set_data has not been called yet.
1042 protected function apply_admin_locked_flags() {
1045 if (!$this->applyadminlockedflags
) {
1049 $settings = get_config($this->_modname
);
1050 $mform = $this->_form
;
1051 $lockedicon = html_writer
::tag('span',
1052 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1053 array('class' => 'action-icon'));
1054 $isupdate = !empty($this->_cm
);
1056 foreach ($settings as $name => $value) {
1057 if (strpos('_', $name) !== false) {
1060 if ($mform->elementExists($name)) {
1061 $element = $mform->getElement($name);
1062 $lockedsetting = $name . '_locked';
1063 if (!empty($settings->$lockedsetting)) {
1064 // Always lock locked settings for new modules,
1065 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1066 $value = $settings->$name;
1067 if ($isupdate && isset($this->current
->$name)) {
1068 $value = $this->current
->$name;
1070 if ($value == $settings->$name) {
1071 $mform->setConstant($name, $settings->$name);
1072 $element->setLabel($element->getLabel() . $lockedicon);
1073 // Do not use hardfreeze because we need the hidden input to check dependencies.
1082 * Get the list of admin settings for this module and apply any defaults/advanced/locked/required settings.
1084 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1085 * default date/time value should be relative to. If not passed, all
1086 * date/time fields are set relative to the users current midnight.
1089 public function apply_admin_defaults($datetimeoffsets = array()) {
1090 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1091 $this->applyadminlockedflags
= true;
1093 $settings = get_config($this->_modname
);
1094 $mform = $this->_form
;
1095 $usermidnight = usergetmidnight(time());
1096 $isupdate = !empty($this->_cm
);
1098 foreach ($settings as $name => $value) {
1099 if (strpos('_', $name) !== false) {
1102 if ($mform->elementExists($name)) {
1103 $element = $mform->getElement($name);
1105 if ($element->getType() == 'date_time_selector') {
1106 $enabledsetting = $name . '_enabled';
1107 if (empty($settings->$enabledsetting)) {
1108 $mform->setDefault($name, 0);
1110 $relativetime = $usermidnight;
1111 if (isset($datetimeoffsets[$name])) {
1112 $relativetime = $datetimeoffsets[$name];
1114 $mform->setDefault($name, $relativetime +
$settings->$name);
1117 $mform->setDefault($name, $settings->$name);
1120 $advancedsetting = $name . '_adv';
1121 if (!empty($settings->$advancedsetting)) {
1122 $mform->setAdvanced($name);
1124 $requiredsetting = $name . '_required';
1125 if (!empty($settings->$requiredsetting)) {
1126 $mform->addRule($name, null, 'required', null, 'client');
1133 * Allows modules to modify the data returned by form get_data().
1134 * This method is also called in the bulk activity completion form.
1136 * Only available on moodleform_mod.
1138 * @param stdClass $data passed by reference
1140 public function data_postprocessing($data) {
1144 * Return submitted data if properly submitted or returns NULL if validation fails or
1145 * if there is no submitted data.
1147 * Do not override this method, override data_postprocessing() instead.
1149 * @return object submitted data; NULL if not valid or not submitted or cancelled
1151 public function get_data() {
1152 $data = parent
::get_data();
1154 // Convert the grade pass value - we may be using a language which uses commas,
1155 // rather than decimal points, in numbers. These need to be converted so that
1156 // they can be added to the DB.
1157 if (isset($data->gradepass
)) {
1158 $data->gradepass
= unformat_float($data->gradepass
);
1161 // Trim name for all activity name.
1162 if (isset($data->name
)) {
1163 $data->name
= trim($data->name
);
1166 $this->data_postprocessing($data);