Merge branch 'MDL-51637-master' of git://github.com/jleyva/moodle
[moodle.git] / course / moodleform_mod.php
blob4c8c25feab79bedaf2359b888ab090ce4ea0a78d
1 <?php
2 require_once ($CFG->libdir.'/formslib.php');
3 require_once($CFG->libdir.'/completionlib.php');
5 /**
6 * This class adds extra methods to form wrapper specific to be used for module
7 * add / update forms mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html
8 */
9 abstract class moodleform_mod extends moodleform {
10 /** Current data */
11 protected $current;
12 /**
13 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
14 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
15 * update one.
17 * @var mixed
19 protected $_instance;
20 /**
21 * Section of course that module instance will be put in or is in.
22 * This is always the section number itself (column 'section' from 'course_sections' table).
24 * @var mixed
26 protected $_section;
27 /**
28 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
29 * update one.
31 * @var mixed
33 protected $_cm;
34 /**
35 * List of modform features
37 protected $_features;
38 /**
39 * @var array Custom completion-rule elements, if enabled
41 protected $_customcompletionelements;
42 /**
43 * @var string name of module
45 protected $_modname;
46 /** current context, course or module depends if already exists*/
47 protected $context;
49 /** a flag indicating whether outcomes are being used*/
50 protected $_outcomesused;
52 /**
53 * @var bool A flag used to indicate that this module should lock settings
54 * based on admin settings flags in definition_after_data.
56 protected $applyadminlockedflags = false;
58 /** @var object The course format of the current course. */
59 protected $courseformat;
61 function moodleform_mod($current, $section, $cm, $course) {
62 global $CFG;
64 $this->current = $current;
65 $this->_instance = $current->instance;
66 $this->_section = $section;
67 $this->_cm = $cm;
68 if ($this->_cm) {
69 $this->context = context_module::instance($this->_cm->id);
70 } else {
71 $this->context = context_course::instance($course->id);
74 // Set the course format.
75 require_once($CFG->dirroot . '/course/format/lib.php');
76 $this->courseformat = course_get_format($course);
78 // Guess module name
79 $matches = array();
80 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
81 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
82 print_error('unknownmodulename');
84 $this->_modname = $matches[1];
85 $this->init_features();
86 parent::moodleform('modedit.php');
89 protected function init_features() {
90 global $CFG;
92 $this->_features = new stdClass();
93 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
94 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
95 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
96 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
97 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
98 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
99 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
100 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
101 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
103 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
104 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
108 * Only available on moodleform_mod.
110 * @param array $default_values passed by reference
112 function data_preprocessing(&$default_values){
113 if (empty($default_values['scale'])) {
114 $default_values['assessed'] = 0;
117 if (empty($default_values['assessed'])){
118 $default_values['ratingtime'] = 0;
119 } else {
120 $default_values['ratingtime']=
121 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
126 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
128 function definition_after_data() {
129 global $CFG, $COURSE;
130 $mform =& $this->_form;
132 if ($id = $mform->getElementValue('update')) {
133 $modulename = $mform->getElementValue('modulename');
134 $instance = $mform->getElementValue('instance');
136 if ($this->_features->gradecat) {
137 $gradecat = false;
138 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
139 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
140 if (!empty($outcomes)) {
141 $gradecat = true;
145 $hasgradeitems = false;
146 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
147 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
148 if (!empty($items)) {
149 foreach ($items as $item) {
150 if (!empty($item->outcomeid)) {
151 $elname = 'outcome_'.$item->outcomeid;
152 if ($mform->elementExists($elname)) {
153 $mform->hardFreeze($elname); // prevent removing of existing outcomes
155 } else {
156 $hasgradeitems = true;
160 foreach ($items as $item) {
161 if (is_bool($gradecat)) {
162 $gradecat = $item->categoryid;
163 continue;
165 if ($gradecat != $item->categoryid) {
166 //mixed categories
167 $gradecat = false;
168 break;
173 if (!$hasgradeitems && $mform->elementExists('gradepass')) {
174 // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
175 $mform->removeElement('gradepass');
178 if ($gradecat === false) {
179 // items and outcomes in different categories - remove the option
180 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
181 if ($mform->elementExists('gradecat')) {
182 $mform->removeElement('gradecat');
183 if ($this->_features->rating && !$mform->elementExists('gradepass')) {
184 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
185 $mform->removeElement('modstandardgrade');
192 if ($COURSE->groupmodeforce) {
193 if ($mform->elementExists('groupmode')) {
194 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
198 // Don't disable/remove groupingid if it is currently set to something,
199 // otherwise you cannot turn it off at same time as turning off other
200 // option (MDL-30764)
201 if (empty($this->_cm) || !$this->_cm->groupingid) {
202 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
203 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
205 } else if (!$mform->elementExists('groupmode')) {
206 // Groupings have no use without groupmode.
207 if ($mform->elementExists('groupingid')) {
208 $mform->removeElement('groupingid');
213 // Completion: If necessary, freeze fields
214 $completion = new completion_info($COURSE);
215 if ($completion->is_enabled()) {
216 // If anybody has completed the activity, these options will be 'locked'
217 $completedcount = empty($this->_cm)
219 : $completion->count_user_data($this->_cm);
221 $freeze = false;
222 if (!$completedcount) {
223 if ($mform->elementExists('unlockcompletion')) {
224 $mform->removeElement('unlockcompletion');
226 // Automatically set to unlocked (note: this is necessary
227 // in order to make it recalculate completion once the option
228 // is changed, maybe someone has completed it now)
229 $mform->getElement('completionunlocked')->setValue(1);
230 } else {
231 // Has the element been unlocked, either by the button being pressed
232 // in this request, or the field already being set from a previous one?
233 if ($mform->exportValue('unlockcompletion') ||
234 $mform->exportValue('completionunlocked')) {
235 // Yes, add in warning text and set the hidden variable
236 $mform->insertElementBefore(
237 $mform->createElement('static', 'completedunlocked',
238 get_string('completedunlocked', 'completion'),
239 get_string('completedunlockedtext', 'completion')),
240 'unlockcompletion');
241 $mform->removeElement('unlockcompletion');
242 $mform->getElement('completionunlocked')->setValue(1);
243 } else {
244 // No, add in the warning text with the count (now we know
245 // it) before the unlock button
246 $mform->insertElementBefore(
247 $mform->createElement('static', 'completedwarning',
248 get_string('completedwarning', 'completion'),
249 get_string('completedwarningtext', 'completion', $completedcount)),
250 'unlockcompletion');
251 $freeze = true;
255 if ($freeze) {
256 $mform->freeze('completion');
257 if ($mform->elementExists('completionview')) {
258 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
260 if ($mform->elementExists('completionusegrade')) {
261 $mform->freeze('completionusegrade');
263 $mform->freeze($this->_customcompletionelements);
267 // Freeze admin defaults if required (and not different from default)
268 $this->apply_admin_locked_flags();
271 // form verification
272 function validation($data, $files) {
273 global $COURSE, $DB, $CFG;
274 $errors = parent::validation($data, $files);
276 $mform =& $this->_form;
278 $errors = array();
280 if ($mform->elementExists('name')) {
281 $name = trim($data['name']);
282 if ($name == '') {
283 $errors['name'] = get_string('required');
287 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
288 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
289 if ($data['coursemodule']) {
290 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
291 } else {
292 $cm = null;
295 if ($mform->elementExists('cmidnumber')) {
296 // verify the idnumber
297 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
298 $errors['cmidnumber'] = get_string('idnumbertaken');
302 // Ratings: Don't let them select an aggregate type without selecting a scale.
303 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
304 // invalid. If ratings have been selected then the user must select either a scale or max points.
305 // This matches (horrible) logic in data_preprocessing.
306 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
307 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
310 // Check that the grade pass is a valid number.
311 $gradepassvalid = false;
312 if (isset($data['gradepass'])) {
313 if (unformat_float($data['gradepass'], true) === false) {
314 $errors['gradepass'] = get_string('err_numeric', 'form');
315 } else {
316 $gradepassvalid = true;
320 // Grade to pass: ensure that the grade to pass is valid for points and scales.
321 // If we are working with a scale, convert into a positive number for validation.
322 if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
323 $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
324 if ($scale < 0) {
325 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
326 $grade = count(explode(',', $scalevalues->scale));
327 } else {
328 $grade = $scale;
330 if ($data['gradepass'] > $grade) {
331 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
335 // Completion: Don't let them choose automatic completion without turning
336 // on some conditions. Ignore this check when completion settings are
337 // locked, as the options are then disabled.
338 if (array_key_exists('completion', $data) &&
339 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
340 !empty($data['completionunlocked'])) {
341 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
342 !$this->completion_rule_enabled($data)) {
343 $errors['completion'] = get_string('badautocompletion', 'completion');
347 // Availability: Check availability field does not have errors.
348 if (!empty($CFG->enableavailability)) {
349 \core_availability\frontend::report_validation_errors($data, $errors);
352 return $errors;
356 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
357 * form definition (new entry form); this function is used to load in data where values
358 * already exist and data is being edited (edit entry form).
360 * @param mixed $default_values object or array of default values
362 function set_data($default_values) {
363 if (is_object($default_values)) {
364 $default_values = (array)$default_values;
367 $this->data_preprocessing($default_values);
368 parent::set_data($default_values);
372 * Adds all the standard elements to a form to edit the settings for an activity module.
374 function standard_coursemodule_elements(){
375 global $COURSE, $CFG, $DB;
376 $mform =& $this->_form;
378 $this->_outcomesused = false;
379 if ($this->_features->outcomes) {
380 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
381 $this->_outcomesused = true;
382 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
383 foreach($outcomes as $outcome) {
384 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
390 if ($this->_features->rating) {
391 require_once($CFG->dirroot.'/rating/lib.php');
392 $rm = new rating_manager();
394 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
396 $permission=CAP_ALLOW;
397 $rolenamestring = null;
398 if (!empty($this->_cm)) {
399 $context = context_module::instance($this->_cm->id);
401 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
402 $rolenamestring = implode(', ', $rolenames);
403 } else {
404 $rolenamestring = get_string('capabilitychecknotavailable','rating');
406 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
407 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
409 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
410 $mform->setDefault('assessed', 0);
411 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
413 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
414 $mform->disabledIf('scale', 'assessed', 'eq', 0);
415 $mform->addHelpButton('scale', 'modgrade', 'grades');
416 $mform->setDefault('scale', $CFG->gradepointdefault);
418 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
419 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
421 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
422 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
423 $mform->disabledIf('assesstimestart', 'ratingtime');
425 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
426 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
427 $mform->disabledIf('assesstimefinish', 'ratingtime');
430 //doing this here means splitting up the grade related settings on the lesson settings page
431 //$this->standard_grading_coursemodule_elements();
433 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
435 $mform->addElement('modvisible', 'visible', get_string('visible'));
436 if (!empty($this->_cm)) {
437 $context = context_module::instance($this->_cm->id);
438 if (!has_capability('moodle/course:activityvisibility', $context)) {
439 $mform->hardFreeze('visible');
443 if ($this->_features->idnumber) {
444 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
445 $mform->setType('cmidnumber', PARAM_RAW);
446 $mform->addHelpButton('cmidnumber', 'idnumbermod');
449 if ($this->_features->groups) {
450 $options = array(NOGROUPS => get_string('groupsnone'),
451 SEPARATEGROUPS => get_string('groupsseparate'),
452 VISIBLEGROUPS => get_string('groupsvisible'));
453 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
454 $mform->addHelpButton('groupmode', 'groupmode', 'group');
457 if ($this->_features->groupings) {
458 // Groupings selector - used to select grouping for groups in activity.
459 $options = array();
460 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
461 foreach ($groupings as $grouping) {
462 $options[$grouping->id] = format_string($grouping->name);
465 core_collator::asort($options);
466 $options = array(0 => get_string('none')) + $options;
467 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
468 $mform->addHelpButton('groupingid', 'grouping', 'group');
471 if (!empty($CFG->enableavailability)) {
472 // Add special button to end of previous section if groups/groupings
473 // are enabled.
474 if ($this->_features->groups || $this->_features->groupings) {
475 $mform->addElement('static', 'restrictgroupbutton', '',
476 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
477 array('id' => 'restrictbygroup', 'disabled' => 'disabled')));
480 // Availability field. This is just a textarea; the user interface
481 // interaction is all implemented in JavaScript.
482 $mform->addElement('header', 'availabilityconditionsheader',
483 get_string('restrictaccess', 'availability'));
484 // Note: This field cannot be named 'availability' because that
485 // conflicts with fields in existing modules (such as assign).
486 // So it uses a long name that will not conflict.
487 $mform->addElement('textarea', 'availabilityconditionsjson',
488 get_string('accessrestrictions', 'availability'));
489 // The _cm variable may not be a proper cm_info, so get one from modinfo.
490 if ($this->_cm) {
491 $modinfo = get_fast_modinfo($COURSE);
492 $cm = $modinfo->get_cm($this->_cm->id);
493 } else {
494 $cm = null;
496 \core_availability\frontend::include_all_javascript($COURSE, $cm);
499 // Conditional activities: completion tracking section
500 if(!isset($completion)) {
501 $completion = new completion_info($COURSE);
503 if ($completion->is_enabled()) {
504 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
506 // Unlock button for if people have completed it (will
507 // be removed in definition_after_data if they haven't)
508 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
509 $mform->registerNoSubmitButton('unlockcompletion');
510 $mform->addElement('hidden', 'completionunlocked', 0);
511 $mform->setType('completionunlocked', PARAM_INT);
513 $trackingdefault = COMPLETION_TRACKING_NONE;
514 // If system and activity default is on, set it.
515 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
516 $trackingdefault = COMPLETION_TRACKING_MANUAL;
519 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
520 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
521 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
522 $mform->setDefault('completion', $trackingdefault);
523 $mform->addHelpButton('completion', 'completion', 'completion');
525 // Automatic completion once you view it
526 $gotcompletionoptions = false;
527 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
528 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
529 get_string('completionview_desc', 'completion'));
530 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
531 $gotcompletionoptions = true;
534 // Automatic completion once it's graded
535 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
536 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
537 get_string('completionusegrade_desc', 'completion'));
538 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
539 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
540 $gotcompletionoptions = true;
542 // If using the rating system, there is no grade unless ratings are enabled.
543 if ($this->_features->rating) {
544 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
548 // Automatic completion according to module-specific rules
549 $this->_customcompletionelements = $this->add_completion_rules();
550 foreach ($this->_customcompletionelements as $element) {
551 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
554 $gotcompletionoptions = $gotcompletionoptions ||
555 count($this->_customcompletionelements)>0;
557 // Automatic option only appears if possible
558 if ($gotcompletionoptions) {
559 $mform->getElement('completion')->addOption(
560 get_string('completion_automatic', 'completion'),
561 COMPLETION_TRACKING_AUTOMATIC);
564 // Completion expected at particular date? (For progress tracking)
565 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
566 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
567 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
570 $this->standard_hidden_coursemodule_elements();
574 * Can be overridden to add custom completion rules if the module wishes
575 * them. If overriding this, you should also override completion_rule_enabled.
576 * <p>
577 * Just add elements to the form as needed and return the list of IDs. The
578 * system will call disabledIf and handle other behaviour for each returned
579 * ID.
580 * @return array Array of string IDs of added items, empty array if none
582 function add_completion_rules() {
583 return array();
587 * Called during validation. Override to indicate, based on the data, whether
588 * a custom completion rule is enabled (selected).
590 * @param array $data Input data (not yet validated)
591 * @return bool True if one or more rules is enabled, false if none are;
592 * default returns false
594 function completion_rule_enabled($data) {
595 return false;
598 function standard_hidden_coursemodule_elements(){
599 $mform =& $this->_form;
600 $mform->addElement('hidden', 'course', 0);
601 $mform->setType('course', PARAM_INT);
603 $mform->addElement('hidden', 'coursemodule', 0);
604 $mform->setType('coursemodule', PARAM_INT);
606 $mform->addElement('hidden', 'section', 0);
607 $mform->setType('section', PARAM_INT);
609 $mform->addElement('hidden', 'module', 0);
610 $mform->setType('module', PARAM_INT);
612 $mform->addElement('hidden', 'modulename', '');
613 $mform->setType('modulename', PARAM_PLUGIN);
615 $mform->addElement('hidden', 'instance', 0);
616 $mform->setType('instance', PARAM_INT);
618 $mform->addElement('hidden', 'add', 0);
619 $mform->setType('add', PARAM_ALPHA);
621 $mform->addElement('hidden', 'update', 0);
622 $mform->setType('update', PARAM_INT);
624 $mform->addElement('hidden', 'return', 0);
625 $mform->setType('return', PARAM_BOOL);
627 $mform->addElement('hidden', 'sr', 0);
628 $mform->setType('sr', PARAM_INT);
631 public function standard_grading_coursemodule_elements() {
632 global $COURSE, $CFG;
633 $mform =& $this->_form;
635 if ($this->_features->hasgrades) {
637 if (!$this->_features->rating || $this->_features->gradecat) {
638 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
641 //if supports grades and grades arent being handled via ratings
642 if (!$this->_features->rating) {
643 $mform->addElement('modgrade', 'grade', get_string('grade'));
644 $mform->addHelpButton('grade', 'modgrade', 'grades');
645 $mform->setDefault('grade', $CFG->gradepointdefault);
648 if ($this->_features->advancedgrading
649 and !empty($this->current->_advancedgradingdata['methods'])
650 and !empty($this->current->_advancedgradingdata['areas'])) {
652 if (count($this->current->_advancedgradingdata['areas']) == 1) {
653 // if there is just one gradable area (most cases), display just the selector
654 // without its name to make UI simplier
655 $areadata = reset($this->current->_advancedgradingdata['areas']);
656 $areaname = key($this->current->_advancedgradingdata['areas']);
657 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
658 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
659 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
660 if (!$this->_features->rating) {
661 $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
664 } else {
665 // the module defines multiple gradable areas, display a selector
666 // for each of them together with a name of the area
667 $areasgroup = array();
668 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
669 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
670 $areadata['title'], $this->current->_advancedgradingdata['methods']);
671 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
673 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
674 array(' ', '<br />'), false);
678 if ($this->_features->gradecat) {
679 $mform->addElement('select', 'gradecat',
680 get_string('gradecategoryonmodform', 'grades'),
681 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
682 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
683 if (!$this->_features->rating) {
684 $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
688 // Grade to pass.
689 $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
690 $mform->addHelpButton('gradepass', 'gradepass', 'grades');
691 $mform->setDefault('gradepass', '');
692 $mform->setType('gradepass', PARAM_RAW);
693 if (!$this->_features->rating) {
694 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
695 } else {
696 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
702 * Add an editor for an activity's introduction field.
703 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
704 * @param null $required Override system default for requiremodintro
705 * @param null $customlabel Override default label for editor
706 * @throws coding_exception
708 protected function add_intro_editor($required=null, $customlabel=null) {
709 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
710 debugging($str, DEBUG_DEVELOPER);
712 $this->standard_intro_elements($customlabel);
717 * Add an editor for an activity's introduction field.
719 * @param null $customlabel Override default label for editor
720 * @throws coding_exception
722 protected function standard_intro_elements($customlabel=null) {
723 global $CFG;
725 $required = $CFG->requiremodintro;
727 $mform = $this->_form;
728 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
730 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
731 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
732 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
733 if ($required) {
734 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
737 // If the 'show description' feature is enabled, this checkbox appears below the intro.
738 // We want to hide that when using the singleactivity course format because it is confusing.
739 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
740 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
741 $mform->addHelpButton('showdescription', 'showdescription');
746 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
748 * @param bool $cancel show cancel button
749 * @param string $submitlabel null means default, false means none, string is label text
750 * @param string $submit2label null means default, false means none, string is label text
751 * @return void
753 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
754 if (is_null($submitlabel)) {
755 $submitlabel = get_string('savechangesanddisplay');
758 if (is_null($submit2label)) {
759 $submit2label = get_string('savechangesandreturntocourse');
762 $mform = $this->_form;
764 // elements in a row need a group
765 $buttonarray = array();
767 // Label for the submit button to return to the course.
768 // Ignore this button in single activity format because it is confusing.
769 if ($submit2label !== false && $this->courseformat->has_view_page()) {
770 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
773 if ($submitlabel !== false) {
774 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
777 if ($cancel) {
778 $buttonarray[] = &$mform->createElement('cancel');
781 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
782 $mform->setType('buttonar', PARAM_RAW);
783 $mform->closeHeaderBefore('buttonar');
787 * Get the list of admin settings for this module and apply any locked settings.
788 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
789 * in that function because set_data has not been called yet.
791 * @return void
793 protected function apply_admin_locked_flags() {
794 global $OUTPUT;
796 if (!$this->applyadminlockedflags) {
797 return;
800 $settings = get_config($this->_modname);
801 $mform = $this->_form;
802 $lockedicon = html_writer::tag('span',
803 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
804 array('class' => 'action-icon'));
805 $isupdate = !empty($this->_cm);
807 foreach ($settings as $name => $value) {
808 if (strpos('_', $name) !== false) {
809 continue;
811 if ($mform->elementExists($name)) {
812 $element = $mform->getElement($name);
813 $lockedsetting = $name . '_locked';
814 if (!empty($settings->$lockedsetting)) {
815 // Always lock locked settings for new modules,
816 // for updates, only lock them if the current value is the same as the default (or there is no current value).
817 $value = $settings->$name;
818 if ($isupdate && isset($this->current->$name)) {
819 $value = $this->current->$name;
821 if ($value == $settings->$name) {
822 $mform->setConstant($name, $settings->$name);
823 $element->setLabel($element->getLabel() . $lockedicon);
824 // Do not use hardfreeze because we need the hidden input to check dependencies.
825 $element->freeze();
833 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
835 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
836 * default date/time value should be relative to. If not passed, all
837 * date/time fields are set relative to the users current midnight.
838 * @return void
840 public function apply_admin_defaults($datetimeoffsets = array()) {
841 // This flag triggers the settings to be locked in apply_admin_locked_flags().
842 $this->applyadminlockedflags = true;
844 $settings = get_config($this->_modname);
845 $mform = $this->_form;
846 $usermidnight = usergetmidnight(time());
847 $isupdate = !empty($this->_cm);
849 foreach ($settings as $name => $value) {
850 if (strpos('_', $name) !== false) {
851 continue;
853 if ($mform->elementExists($name)) {
854 $element = $mform->getElement($name);
855 if (!$isupdate) {
856 if ($element->getType() == 'date_time_selector') {
857 $enabledsetting = $name . '_enabled';
858 if (empty($settings->$enabledsetting)) {
859 $mform->setDefault($name, 0);
860 } else {
861 $relativetime = $usermidnight;
862 if (isset($datetimeoffsets[$name])) {
863 $relativetime = $datetimeoffsets[$name];
865 $mform->setDefault($name, $relativetime + $settings->$name);
867 } else {
868 $mform->setDefault($name, $settings->$name);
871 $advancedsetting = $name . '_adv';
872 if (!empty($settings->$advancedsetting)) {
873 $mform->setAdvanced($name);