Moodle release 2.7.4
[moodle.git] / course / moodleform_mod.php
blob7652f13eb1032de396beac8991f7731e79c4bd72
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->groupmembersonly = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
96 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
97 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
98 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
99 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
100 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
101 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
102 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
104 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
105 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
109 * Only available on moodleform_mod.
111 * @param array $default_values passed by reference
113 function data_preprocessing(&$default_values){
114 if (empty($default_values['scale'])) {
115 $default_values['assessed'] = 0;
118 if (empty($default_values['assessed'])){
119 $default_values['ratingtime'] = 0;
120 } else {
121 $default_values['ratingtime']=
122 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
127 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
129 function definition_after_data() {
130 global $CFG, $COURSE;
131 $mform =& $this->_form;
133 if ($id = $mform->getElementValue('update')) {
134 $modulename = $mform->getElementValue('modulename');
135 $instance = $mform->getElementValue('instance');
137 if ($this->_features->gradecat) {
138 $gradecat = false;
139 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
140 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
141 if (!empty($outcomes)) {
142 $gradecat = true;
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
158 foreach ($items as $item) {
159 if (is_bool($gradecat)) {
160 $gradecat = $item->categoryid;
161 continue;
163 if ($gradecat != $item->categoryid) {
164 //mixed categories
165 $gradecat = false;
166 break;
171 if ($gradecat === false) {
172 // items and outcomes in different categories - remove the option
173 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
174 if ($mform->elementExists('gradecat')) {
175 $mform->removeElement('gradecat');
176 if ($this->_features->rating) {
177 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
178 $mform->removeElement('modstandardgrade');
185 if ($COURSE->groupmodeforce) {
186 if ($mform->elementExists('groupmode')) {
187 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
191 // Don't disable/remove groupingid if it is currently set to something,
192 // otherwise you cannot turn it off at same time as turning off other
193 // option (MDL-30764)
194 if (empty($this->_cm) || !$this->_cm->groupingid) {
195 if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
196 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
198 } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
199 $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
201 } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
202 // groupings have no use without groupmode or groupmembersonly
203 if ($mform->elementExists('groupingid')) {
204 $mform->removeElement('groupingid');
209 // Completion: If necessary, freeze fields
210 $completion = new completion_info($COURSE);
211 if ($completion->is_enabled()) {
212 // If anybody has completed the activity, these options will be 'locked'
213 $completedcount = empty($this->_cm)
215 : $completion->count_user_data($this->_cm);
217 $freeze = false;
218 if (!$completedcount) {
219 if ($mform->elementExists('unlockcompletion')) {
220 $mform->removeElement('unlockcompletion');
222 // Automatically set to unlocked (note: this is necessary
223 // in order to make it recalculate completion once the option
224 // is changed, maybe someone has completed it now)
225 $mform->getElement('completionunlocked')->setValue(1);
226 } else {
227 // Has the element been unlocked, either by the button being pressed
228 // in this request, or the field already being set from a previous one?
229 if ($mform->exportValue('unlockcompletion') ||
230 $mform->exportValue('completionunlocked')) {
231 // Yes, add in warning text and set the hidden variable
232 $mform->insertElementBefore(
233 $mform->createElement('static', 'completedunlocked',
234 get_string('completedunlocked', 'completion'),
235 get_string('completedunlockedtext', 'completion')),
236 'unlockcompletion');
237 $mform->removeElement('unlockcompletion');
238 $mform->getElement('completionunlocked')->setValue(1);
239 } else {
240 // No, add in the warning text with the count (now we know
241 // it) before the unlock button
242 $mform->insertElementBefore(
243 $mform->createElement('static', 'completedwarning',
244 get_string('completedwarning', 'completion'),
245 get_string('completedwarningtext', 'completion', $completedcount)),
246 'unlockcompletion');
247 $freeze = true;
251 if ($freeze) {
252 $mform->freeze('completion');
253 if ($mform->elementExists('completionview')) {
254 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
256 if ($mform->elementExists('completionusegrade')) {
257 $mform->freeze('completionusegrade');
259 $mform->freeze($this->_customcompletionelements);
263 // Freeze admin defaults if required (and not different from default)
264 $this->apply_admin_locked_flags();
267 // form verification
268 function validation($data, $files) {
269 global $COURSE, $DB, $CFG;
270 $errors = parent::validation($data, $files);
272 $mform =& $this->_form;
274 $errors = array();
276 if ($mform->elementExists('name')) {
277 $name = trim($data['name']);
278 if ($name == '') {
279 $errors['name'] = get_string('required');
283 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
284 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
285 if ($data['coursemodule']) {
286 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
287 } else {
288 $cm = null;
291 if ($mform->elementExists('cmidnumber')) {
292 // verify the idnumber
293 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
294 $errors['cmidnumber'] = get_string('idnumbertaken');
298 // Ratings: Don't let them select an aggregate type without selecting a scale.
299 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
300 // invalid. If ratings have been selected then the user must select either a scale or max points.
301 // This matches (horrible) logic in data_preprocessing.
302 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
303 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
306 // Completion: Don't let them choose automatic completion without turning
307 // on some conditions. Ignore this check when completion settings are
308 // locked, as the options are then disabled.
309 if (array_key_exists('completion', $data) &&
310 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
311 !empty($data['completionunlocked'])) {
312 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
313 !$this->completion_rule_enabled($data)) {
314 $errors['completion'] = get_string('badautocompletion', 'completion');
318 // Availability: Check availability field does not have errors.
319 if (!empty($CFG->enableavailability)) {
320 \core_availability\frontend::report_validation_errors($data, $errors);
323 return $errors;
327 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
328 * form definition (new entry form); this function is used to load in data where values
329 * already exist and data is being edited (edit entry form).
331 * @param mixed $default_values object or array of default values
333 function set_data($default_values) {
334 if (is_object($default_values)) {
335 $default_values = (array)$default_values;
338 $this->data_preprocessing($default_values);
339 parent::set_data($default_values);
343 * Adds all the standard elements to a form to edit the settings for an activity module.
345 function standard_coursemodule_elements(){
346 global $COURSE, $CFG, $DB;
347 $mform =& $this->_form;
349 $this->_outcomesused = false;
350 if ($this->_features->outcomes) {
351 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
352 $this->_outcomesused = true;
353 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
354 foreach($outcomes as $outcome) {
355 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
361 if ($this->_features->rating) {
362 require_once($CFG->dirroot.'/rating/lib.php');
363 $rm = new rating_manager();
365 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
367 $permission=CAP_ALLOW;
368 $rolenamestring = null;
369 if (!empty($this->_cm)) {
370 $context = context_module::instance($this->_cm->id);
372 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
373 $rolenamestring = implode(', ', $rolenames);
374 } else {
375 $rolenamestring = get_string('capabilitychecknotavailable','rating');
377 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
378 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
380 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
381 $mform->setDefault('assessed', 0);
382 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
384 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
385 $mform->disabledIf('scale', 'assessed', 'eq', 0);
386 $mform->addHelpButton('scale', 'modgrade', 'grades');
387 $mform->setDefault('scale', $CFG->gradepointdefault);
389 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
390 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
392 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
393 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
394 $mform->disabledIf('assesstimestart', 'ratingtime');
396 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
397 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
398 $mform->disabledIf('assesstimefinish', 'ratingtime');
401 //doing this here means splitting up the grade related settings on the lesson settings page
402 //$this->standard_grading_coursemodule_elements();
404 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
406 $mform->addElement('modvisible', 'visible', get_string('visible'));
407 if (!empty($this->_cm)) {
408 $context = context_module::instance($this->_cm->id);
409 if (!has_capability('moodle/course:activityvisibility', $context)) {
410 $mform->hardFreeze('visible');
414 if ($this->_features->idnumber) {
415 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
416 $mform->setType('cmidnumber', PARAM_RAW);
417 $mform->addHelpButton('cmidnumber', 'idnumbermod');
420 if ($this->_features->groups) {
421 $options = array(NOGROUPS => get_string('groupsnone'),
422 SEPARATEGROUPS => get_string('groupsseparate'),
423 VISIBLEGROUPS => get_string('groupsvisible'));
424 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
425 $mform->addHelpButton('groupmode', 'groupmode', 'group');
428 if ($this->_features->groupings or $this->_features->groupmembersonly) {
429 //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
430 $options = array();
431 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
432 foreach ($groupings as $grouping) {
433 $options[$grouping->id] = format_string($grouping->name);
436 core_collator::asort($options);
437 $options = array(0 => get_string('none')) + $options;
438 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
439 $mform->addHelpButton('groupingid', 'grouping', 'group');
442 if ($this->_features->groupmembersonly) {
443 $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
444 $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
447 if (!empty($CFG->enableavailability)) {
448 // Availability field. This is just a textarea; the user interface
449 // interaction is all implemented in JavaScript.
450 $mform->addElement('header', 'availabilityconditionsheader',
451 get_string('restrictaccess', 'availability'));
452 // Note: This field cannot be named 'availability' because that
453 // conflicts with fields in existing modules (such as assign).
454 // So it uses a long name that will not conflict.
455 $mform->addElement('textarea', 'availabilityconditionsjson',
456 get_string('accessrestrictions', 'availability'));
457 // The _cm variable may not be a proper cm_info, so get one from modinfo.
458 if ($this->_cm) {
459 $modinfo = get_fast_modinfo($COURSE);
460 $cm = $modinfo->get_cm($this->_cm->id);
461 } else {
462 $cm = null;
464 \core_availability\frontend::include_all_javascript($COURSE, $cm);
467 // Conditional activities: completion tracking section
468 if(!isset($completion)) {
469 $completion = new completion_info($COURSE);
471 if ($completion->is_enabled()) {
472 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
474 // Unlock button for if people have completed it (will
475 // be removed in definition_after_data if they haven't)
476 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
477 $mform->registerNoSubmitButton('unlockcompletion');
478 $mform->addElement('hidden', 'completionunlocked', 0);
479 $mform->setType('completionunlocked', PARAM_INT);
481 $trackingdefault = COMPLETION_TRACKING_NONE;
482 // If system and activity default is on, set it.
483 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
484 $trackingdefault = COMPLETION_TRACKING_MANUAL;
487 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
488 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
489 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
490 $mform->setDefault('completion', $trackingdefault);
491 $mform->addHelpButton('completion', 'completion', 'completion');
493 // Automatic completion once you view it
494 $gotcompletionoptions = false;
495 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
496 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
497 get_string('completionview_desc', 'completion'));
498 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
499 $gotcompletionoptions = true;
502 // Automatic completion once it's graded
503 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
504 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
505 get_string('completionusegrade_desc', 'completion'));
506 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
507 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
508 $gotcompletionoptions = true;
510 // If using the rating system, there is no grade unless ratings are enabled.
511 if ($this->_features->rating) {
512 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
516 // Automatic completion according to module-specific rules
517 $this->_customcompletionelements = $this->add_completion_rules();
518 foreach ($this->_customcompletionelements as $element) {
519 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
522 $gotcompletionoptions = $gotcompletionoptions ||
523 count($this->_customcompletionelements)>0;
525 // Automatic option only appears if possible
526 if ($gotcompletionoptions) {
527 $mform->getElement('completion')->addOption(
528 get_string('completion_automatic', 'completion'),
529 COMPLETION_TRACKING_AUTOMATIC);
532 // Completion expected at particular date? (For progress tracking)
533 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
534 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
535 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
538 $this->standard_hidden_coursemodule_elements();
542 * Can be overridden to add custom completion rules if the module wishes
543 * them. If overriding this, you should also override completion_rule_enabled.
544 * <p>
545 * Just add elements to the form as needed and return the list of IDs. The
546 * system will call disabledIf and handle other behaviour for each returned
547 * ID.
548 * @return array Array of string IDs of added items, empty array if none
550 function add_completion_rules() {
551 return array();
555 * Called during validation. Override to indicate, based on the data, whether
556 * a custom completion rule is enabled (selected).
558 * @param array $data Input data (not yet validated)
559 * @return bool True if one or more rules is enabled, false if none are;
560 * default returns false
562 function completion_rule_enabled($data) {
563 return false;
566 function standard_hidden_coursemodule_elements(){
567 $mform =& $this->_form;
568 $mform->addElement('hidden', 'course', 0);
569 $mform->setType('course', PARAM_INT);
571 $mform->addElement('hidden', 'coursemodule', 0);
572 $mform->setType('coursemodule', PARAM_INT);
574 $mform->addElement('hidden', 'section', 0);
575 $mform->setType('section', PARAM_INT);
577 $mform->addElement('hidden', 'module', 0);
578 $mform->setType('module', PARAM_INT);
580 $mform->addElement('hidden', 'modulename', '');
581 $mform->setType('modulename', PARAM_PLUGIN);
583 $mform->addElement('hidden', 'instance', 0);
584 $mform->setType('instance', PARAM_INT);
586 $mform->addElement('hidden', 'add', 0);
587 $mform->setType('add', PARAM_ALPHA);
589 $mform->addElement('hidden', 'update', 0);
590 $mform->setType('update', PARAM_INT);
592 $mform->addElement('hidden', 'return', 0);
593 $mform->setType('return', PARAM_BOOL);
595 $mform->addElement('hidden', 'sr', 0);
596 $mform->setType('sr', PARAM_INT);
599 public function standard_grading_coursemodule_elements() {
600 global $COURSE, $CFG;
601 $mform =& $this->_form;
603 if ($this->_features->hasgrades) {
605 if (!$this->_features->rating || $this->_features->gradecat) {
606 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
609 //if supports grades and grades arent being handled via ratings
610 if (!$this->_features->rating) {
611 $mform->addElement('modgrade', 'grade', get_string('grade'));
612 $mform->addHelpButton('grade', 'modgrade', 'grades');
613 $mform->setDefault('grade', $CFG->gradepointdefault);
616 if ($this->_features->advancedgrading
617 and !empty($this->current->_advancedgradingdata['methods'])
618 and !empty($this->current->_advancedgradingdata['areas'])) {
620 if (count($this->current->_advancedgradingdata['areas']) == 1) {
621 // if there is just one gradable area (most cases), display just the selector
622 // without its name to make UI simplier
623 $areadata = reset($this->current->_advancedgradingdata['areas']);
624 $areaname = key($this->current->_advancedgradingdata['areas']);
625 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
626 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
627 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
629 } else {
630 // the module defines multiple gradable areas, display a selector
631 // for each of them together with a name of the area
632 $areasgroup = array();
633 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
634 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
635 $areadata['title'], $this->current->_advancedgradingdata['methods']);
636 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
638 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
639 array(' ', '<br />'), false);
643 if ($this->_features->gradecat) {
644 $mform->addElement('select', 'gradecat',
645 get_string('gradecategoryonmodform', 'grades'),
646 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
647 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
652 function add_intro_editor($required=false, $customlabel=null) {
653 if (!$this->_features->introeditor) {
654 // intro editor not supported in this module
655 return;
658 $mform = $this->_form;
659 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
661 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
662 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
663 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
664 if ($required) {
665 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
668 // If the 'show description' feature is enabled, this checkbox appears below the intro.
669 // We want to hide that when using the singleactivity course format because it is confusing.
670 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
671 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
672 $mform->addHelpButton('showdescription', 'showdescription');
677 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
679 * @param bool $cancel show cancel button
680 * @param string $submitlabel null means default, false means none, string is label text
681 * @param string $submit2label null means default, false means none, string is label text
682 * @return void
684 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
685 if (is_null($submitlabel)) {
686 $submitlabel = get_string('savechangesanddisplay');
689 if (is_null($submit2label)) {
690 $submit2label = get_string('savechangesandreturntocourse');
693 $mform = $this->_form;
695 // elements in a row need a group
696 $buttonarray = array();
698 // Label for the submit button to return to the course.
699 // Ignore this button in single activity format because it is confusing.
700 if ($submit2label !== false && $this->courseformat->has_view_page()) {
701 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
704 if ($submitlabel !== false) {
705 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
708 if ($cancel) {
709 $buttonarray[] = &$mform->createElement('cancel');
712 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
713 $mform->setType('buttonar', PARAM_RAW);
714 $mform->closeHeaderBefore('buttonar');
718 * Get the list of admin settings for this module and apply any locked settings.
719 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
720 * in that function because set_data has not been called yet.
722 * @return void
724 protected function apply_admin_locked_flags() {
725 global $OUTPUT;
727 if (!$this->applyadminlockedflags) {
728 return;
731 $settings = get_config($this->_modname);
732 $mform = $this->_form;
733 $lockedicon = html_writer::tag('span',
734 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
735 array('class' => 'action-icon'));
736 $isupdate = !empty($this->_cm);
738 foreach ($settings as $name => $value) {
739 if (strpos('_', $name) !== false) {
740 continue;
742 if ($mform->elementExists($name)) {
743 $element = $mform->getElement($name);
744 $lockedsetting = $name . '_locked';
745 if (!empty($settings->$lockedsetting)) {
746 // Always lock locked settings for new modules,
747 // for updates, only lock them if the current value is the same as the default (or there is no current value).
748 $value = $settings->$name;
749 if ($isupdate && isset($this->current->$name)) {
750 $value = $this->current->$name;
752 if ($value == $settings->$name) {
753 $mform->setConstant($name, $settings->$name);
754 $element->setLabel($element->getLabel() . $lockedicon);
755 // Do not use hardfreeze because we need the hidden input to check dependencies.
756 $element->freeze();
764 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
766 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
767 * default date/time value should be relative to. If not passed, all
768 * date/time fields are set relative to the users current midnight.
769 * @return void
771 public function apply_admin_defaults($datetimeoffsets = array()) {
772 // This flag triggers the settings to be locked in apply_admin_locked_flags().
773 $this->applyadminlockedflags = true;
775 $settings = get_config($this->_modname);
776 $mform = $this->_form;
777 $usermidnight = usergetmidnight(time());
778 $isupdate = !empty($this->_cm);
780 foreach ($settings as $name => $value) {
781 if (strpos('_', $name) !== false) {
782 continue;
784 if ($mform->elementExists($name)) {
785 $element = $mform->getElement($name);
786 if (!$isupdate) {
787 if ($element->getType() == 'date_time_selector') {
788 $enabledsetting = $name . '_enabled';
789 if (empty($settings->$enabledsetting)) {
790 $mform->setDefault($name, 0);
791 } else {
792 $relativetime = $usermidnight;
793 if (isset($datetimeoffsets[$name])) {
794 $relativetime = $datetimeoffsets[$name];
796 $mform->setDefault($name, $relativetime + $settings->$name);
798 } else {
799 $mform->setDefault($name, $settings->$name);
802 $advancedsetting = $name . '_adv';
803 if (!empty($settings->$advancedsetting)) {
804 $mform->setAdvanced($name);