MDL-48474 qtype_shortanswer: answers were not being trimmed.
[moodle.git] / course / moodleform_mod.php
blob6a3a845ff3eaca9f9b154e9142b790e281f54c8e
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 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
146 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
147 if (!empty($items)) {
148 foreach ($items as $item) {
149 if (!empty($item->outcomeid)) {
150 $elname = 'outcome_'.$item->outcomeid;
151 if ($mform->elementExists($elname)) {
152 $mform->hardFreeze($elname); // prevent removing of existing outcomes
157 foreach ($items as $item) {
158 if (is_bool($gradecat)) {
159 $gradecat = $item->categoryid;
160 continue;
162 if ($gradecat != $item->categoryid) {
163 //mixed categories
164 $gradecat = false;
165 break;
170 if ($gradecat === false) {
171 // items and outcomes in different categories - remove the option
172 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
173 if ($mform->elementExists('gradecat')) {
174 $mform->removeElement('gradecat');
175 if ($this->_features->rating) {
176 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
177 $mform->removeElement('modstandardgrade');
184 if ($COURSE->groupmodeforce) {
185 if ($mform->elementExists('groupmode')) {
186 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
190 // Don't disable/remove groupingid if it is currently set to something,
191 // otherwise you cannot turn it off at same time as turning off other
192 // option (MDL-30764)
193 if (empty($this->_cm) || !$this->_cm->groupingid) {
194 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
195 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
197 } else if (!$mform->elementExists('groupmode')) {
198 // Groupings have no use without groupmode.
199 if ($mform->elementExists('groupingid')) {
200 $mform->removeElement('groupingid');
205 // Completion: If necessary, freeze fields
206 $completion = new completion_info($COURSE);
207 if ($completion->is_enabled()) {
208 // If anybody has completed the activity, these options will be 'locked'
209 $completedcount = empty($this->_cm)
211 : $completion->count_user_data($this->_cm);
213 $freeze = false;
214 if (!$completedcount) {
215 if ($mform->elementExists('unlockcompletion')) {
216 $mform->removeElement('unlockcompletion');
218 // Automatically set to unlocked (note: this is necessary
219 // in order to make it recalculate completion once the option
220 // is changed, maybe someone has completed it now)
221 $mform->getElement('completionunlocked')->setValue(1);
222 } else {
223 // Has the element been unlocked, either by the button being pressed
224 // in this request, or the field already being set from a previous one?
225 if ($mform->exportValue('unlockcompletion') ||
226 $mform->exportValue('completionunlocked')) {
227 // Yes, add in warning text and set the hidden variable
228 $mform->insertElementBefore(
229 $mform->createElement('static', 'completedunlocked',
230 get_string('completedunlocked', 'completion'),
231 get_string('completedunlockedtext', 'completion')),
232 'unlockcompletion');
233 $mform->removeElement('unlockcompletion');
234 $mform->getElement('completionunlocked')->setValue(1);
235 } else {
236 // No, add in the warning text with the count (now we know
237 // it) before the unlock button
238 $mform->insertElementBefore(
239 $mform->createElement('static', 'completedwarning',
240 get_string('completedwarning', 'completion'),
241 get_string('completedwarningtext', 'completion', $completedcount)),
242 'unlockcompletion');
243 $freeze = true;
247 if ($freeze) {
248 $mform->freeze('completion');
249 if ($mform->elementExists('completionview')) {
250 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
252 if ($mform->elementExists('completionusegrade')) {
253 $mform->freeze('completionusegrade');
255 $mform->freeze($this->_customcompletionelements);
259 // Freeze admin defaults if required (and not different from default)
260 $this->apply_admin_locked_flags();
263 // form verification
264 function validation($data, $files) {
265 global $COURSE, $DB, $CFG;
266 $errors = parent::validation($data, $files);
268 $mform =& $this->_form;
270 $errors = array();
272 if ($mform->elementExists('name')) {
273 $name = trim($data['name']);
274 if ($name == '') {
275 $errors['name'] = get_string('required');
279 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
280 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
281 if ($data['coursemodule']) {
282 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
283 } else {
284 $cm = null;
287 if ($mform->elementExists('cmidnumber')) {
288 // verify the idnumber
289 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
290 $errors['cmidnumber'] = get_string('idnumbertaken');
294 // Ratings: Don't let them select an aggregate type without selecting a scale.
295 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
296 // invalid. If ratings have been selected then the user must select either a scale or max points.
297 // This matches (horrible) logic in data_preprocessing.
298 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
299 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
302 // Completion: Don't let them choose automatic completion without turning
303 // on some conditions. Ignore this check when completion settings are
304 // locked, as the options are then disabled.
305 if (array_key_exists('completion', $data) &&
306 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
307 !empty($data['completionunlocked'])) {
308 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
309 !$this->completion_rule_enabled($data)) {
310 $errors['completion'] = get_string('badautocompletion', 'completion');
314 // Availability: Check availability field does not have errors.
315 if (!empty($CFG->enableavailability)) {
316 \core_availability\frontend::report_validation_errors($data, $errors);
319 return $errors;
323 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
324 * form definition (new entry form); this function is used to load in data where values
325 * already exist and data is being edited (edit entry form).
327 * @param mixed $default_values object or array of default values
329 function set_data($default_values) {
330 if (is_object($default_values)) {
331 $default_values = (array)$default_values;
334 $this->data_preprocessing($default_values);
335 parent::set_data($default_values);
339 * Adds all the standard elements to a form to edit the settings for an activity module.
341 function standard_coursemodule_elements(){
342 global $COURSE, $CFG, $DB;
343 $mform =& $this->_form;
345 $this->_outcomesused = false;
346 if ($this->_features->outcomes) {
347 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
348 $this->_outcomesused = true;
349 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
350 foreach($outcomes as $outcome) {
351 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
357 if ($this->_features->rating) {
358 require_once($CFG->dirroot.'/rating/lib.php');
359 $rm = new rating_manager();
361 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
363 $permission=CAP_ALLOW;
364 $rolenamestring = null;
365 if (!empty($this->_cm)) {
366 $context = context_module::instance($this->_cm->id);
368 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
369 $rolenamestring = implode(', ', $rolenames);
370 } else {
371 $rolenamestring = get_string('capabilitychecknotavailable','rating');
373 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
374 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
376 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
377 $mform->setDefault('assessed', 0);
378 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
380 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
381 $mform->disabledIf('scale', 'assessed', 'eq', 0);
382 $mform->addHelpButton('scale', 'modgrade', 'grades');
383 $mform->setDefault('scale', $CFG->gradepointdefault);
385 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
386 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
388 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
389 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
390 $mform->disabledIf('assesstimestart', 'ratingtime');
392 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
393 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
394 $mform->disabledIf('assesstimefinish', 'ratingtime');
397 //doing this here means splitting up the grade related settings on the lesson settings page
398 //$this->standard_grading_coursemodule_elements();
400 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
402 $mform->addElement('modvisible', 'visible', get_string('visible'));
403 if (!empty($this->_cm)) {
404 $context = context_module::instance($this->_cm->id);
405 if (!has_capability('moodle/course:activityvisibility', $context)) {
406 $mform->hardFreeze('visible');
410 if ($this->_features->idnumber) {
411 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
412 $mform->setType('cmidnumber', PARAM_RAW);
413 $mform->addHelpButton('cmidnumber', 'idnumbermod');
416 if ($this->_features->groups) {
417 $options = array(NOGROUPS => get_string('groupsnone'),
418 SEPARATEGROUPS => get_string('groupsseparate'),
419 VISIBLEGROUPS => get_string('groupsvisible'));
420 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
421 $mform->addHelpButton('groupmode', 'groupmode', 'group');
424 if ($this->_features->groupings) {
425 // Groupings selector - used to select grouping for groups in activity.
426 $options = array();
427 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
428 foreach ($groupings as $grouping) {
429 $options[$grouping->id] = format_string($grouping->name);
432 core_collator::asort($options);
433 $options = array(0 => get_string('none')) + $options;
434 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
435 $mform->addHelpButton('groupingid', 'grouping', 'group');
438 if (!empty($CFG->enableavailability)) {
439 // Add special button to end of previous section if groups/groupings
440 // are enabled.
441 if ($this->_features->groups || $this->_features->groupings) {
442 $mform->addElement('static', 'restrictgroupbutton', '',
443 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
444 array('id' => 'restrictbygroup', 'disabled' => 'disabled')));
447 // Availability field. This is just a textarea; the user interface
448 // interaction is all implemented in JavaScript.
449 $mform->addElement('header', 'availabilityconditionsheader',
450 get_string('restrictaccess', 'availability'));
451 // Note: This field cannot be named 'availability' because that
452 // conflicts with fields in existing modules (such as assign).
453 // So it uses a long name that will not conflict.
454 $mform->addElement('textarea', 'availabilityconditionsjson',
455 get_string('accessrestrictions', 'availability'));
456 // The _cm variable may not be a proper cm_info, so get one from modinfo.
457 if ($this->_cm) {
458 $modinfo = get_fast_modinfo($COURSE);
459 $cm = $modinfo->get_cm($this->_cm->id);
460 } else {
461 $cm = null;
463 \core_availability\frontend::include_all_javascript($COURSE, $cm);
466 // Conditional activities: completion tracking section
467 if(!isset($completion)) {
468 $completion = new completion_info($COURSE);
470 if ($completion->is_enabled()) {
471 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
473 // Unlock button for if people have completed it (will
474 // be removed in definition_after_data if they haven't)
475 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
476 $mform->registerNoSubmitButton('unlockcompletion');
477 $mform->addElement('hidden', 'completionunlocked', 0);
478 $mform->setType('completionunlocked', PARAM_INT);
480 $trackingdefault = COMPLETION_TRACKING_NONE;
481 // If system and activity default is on, set it.
482 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
483 $trackingdefault = COMPLETION_TRACKING_MANUAL;
486 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
487 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
488 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
489 $mform->setDefault('completion', $trackingdefault);
490 $mform->addHelpButton('completion', 'completion', 'completion');
492 // Automatic completion once you view it
493 $gotcompletionoptions = false;
494 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
495 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
496 get_string('completionview_desc', 'completion'));
497 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
498 $gotcompletionoptions = true;
501 // Automatic completion once it's graded
502 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
503 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
504 get_string('completionusegrade_desc', 'completion'));
505 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
506 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
507 $gotcompletionoptions = true;
509 // If using the rating system, there is no grade unless ratings are enabled.
510 if ($this->_features->rating) {
511 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
515 // Automatic completion according to module-specific rules
516 $this->_customcompletionelements = $this->add_completion_rules();
517 foreach ($this->_customcompletionelements as $element) {
518 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
521 $gotcompletionoptions = $gotcompletionoptions ||
522 count($this->_customcompletionelements)>0;
524 // Automatic option only appears if possible
525 if ($gotcompletionoptions) {
526 $mform->getElement('completion')->addOption(
527 get_string('completion_automatic', 'completion'),
528 COMPLETION_TRACKING_AUTOMATIC);
531 // Completion expected at particular date? (For progress tracking)
532 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
533 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
534 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
537 $this->standard_hidden_coursemodule_elements();
541 * Can be overridden to add custom completion rules if the module wishes
542 * them. If overriding this, you should also override completion_rule_enabled.
543 * <p>
544 * Just add elements to the form as needed and return the list of IDs. The
545 * system will call disabledIf and handle other behaviour for each returned
546 * ID.
547 * @return array Array of string IDs of added items, empty array if none
549 function add_completion_rules() {
550 return array();
554 * Called during validation. Override to indicate, based on the data, whether
555 * a custom completion rule is enabled (selected).
557 * @param array $data Input data (not yet validated)
558 * @return bool True if one or more rules is enabled, false if none are;
559 * default returns false
561 function completion_rule_enabled($data) {
562 return false;
565 function standard_hidden_coursemodule_elements(){
566 $mform =& $this->_form;
567 $mform->addElement('hidden', 'course', 0);
568 $mform->setType('course', PARAM_INT);
570 $mform->addElement('hidden', 'coursemodule', 0);
571 $mform->setType('coursemodule', PARAM_INT);
573 $mform->addElement('hidden', 'section', 0);
574 $mform->setType('section', PARAM_INT);
576 $mform->addElement('hidden', 'module', 0);
577 $mform->setType('module', PARAM_INT);
579 $mform->addElement('hidden', 'modulename', '');
580 $mform->setType('modulename', PARAM_PLUGIN);
582 $mform->addElement('hidden', 'instance', 0);
583 $mform->setType('instance', PARAM_INT);
585 $mform->addElement('hidden', 'add', 0);
586 $mform->setType('add', PARAM_ALPHA);
588 $mform->addElement('hidden', 'update', 0);
589 $mform->setType('update', PARAM_INT);
591 $mform->addElement('hidden', 'return', 0);
592 $mform->setType('return', PARAM_BOOL);
594 $mform->addElement('hidden', 'sr', 0);
595 $mform->setType('sr', PARAM_INT);
598 public function standard_grading_coursemodule_elements() {
599 global $COURSE, $CFG;
600 $mform =& $this->_form;
602 if ($this->_features->hasgrades) {
604 if (!$this->_features->rating || $this->_features->gradecat) {
605 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
608 //if supports grades and grades arent being handled via ratings
609 if (!$this->_features->rating) {
610 $mform->addElement('modgrade', 'grade', get_string('grade'));
611 $mform->addHelpButton('grade', 'modgrade', 'grades');
612 $mform->setDefault('grade', $CFG->gradepointdefault);
615 if ($this->_features->advancedgrading
616 and !empty($this->current->_advancedgradingdata['methods'])
617 and !empty($this->current->_advancedgradingdata['areas'])) {
619 if (count($this->current->_advancedgradingdata['areas']) == 1) {
620 // if there is just one gradable area (most cases), display just the selector
621 // without its name to make UI simplier
622 $areadata = reset($this->current->_advancedgradingdata['areas']);
623 $areaname = key($this->current->_advancedgradingdata['areas']);
624 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
625 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
626 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
628 } else {
629 // the module defines multiple gradable areas, display a selector
630 // for each of them together with a name of the area
631 $areasgroup = array();
632 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
633 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
634 $areadata['title'], $this->current->_advancedgradingdata['methods']);
635 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
637 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
638 array(' ', '<br />'), false);
642 if ($this->_features->gradecat) {
643 $mform->addElement('select', 'gradecat',
644 get_string('gradecategoryonmodform', 'grades'),
645 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
646 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
651 function add_intro_editor($required=false, $customlabel=null) {
652 if (!$this->_features->introeditor) {
653 // intro editor not supported in this module
654 return;
657 $mform = $this->_form;
658 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
660 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
661 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
662 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
663 if ($required) {
664 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
667 // If the 'show description' feature is enabled, this checkbox appears below the intro.
668 // We want to hide that when using the singleactivity course format because it is confusing.
669 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
670 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
671 $mform->addHelpButton('showdescription', 'showdescription');
676 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
678 * @param bool $cancel show cancel button
679 * @param string $submitlabel null means default, false means none, string is label text
680 * @param string $submit2label null means default, false means none, string is label text
681 * @return void
683 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
684 if (is_null($submitlabel)) {
685 $submitlabel = get_string('savechangesanddisplay');
688 if (is_null($submit2label)) {
689 $submit2label = get_string('savechangesandreturntocourse');
692 $mform = $this->_form;
694 // elements in a row need a group
695 $buttonarray = array();
697 // Label for the submit button to return to the course.
698 // Ignore this button in single activity format because it is confusing.
699 if ($submit2label !== false && $this->courseformat->has_view_page()) {
700 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
703 if ($submitlabel !== false) {
704 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
707 if ($cancel) {
708 $buttonarray[] = &$mform->createElement('cancel');
711 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
712 $mform->setType('buttonar', PARAM_RAW);
713 $mform->closeHeaderBefore('buttonar');
717 * Get the list of admin settings for this module and apply any locked settings.
718 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
719 * in that function because set_data has not been called yet.
721 * @return void
723 protected function apply_admin_locked_flags() {
724 global $OUTPUT;
726 if (!$this->applyadminlockedflags) {
727 return;
730 $settings = get_config($this->_modname);
731 $mform = $this->_form;
732 $lockedicon = html_writer::tag('span',
733 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
734 array('class' => 'action-icon'));
735 $isupdate = !empty($this->_cm);
737 foreach ($settings as $name => $value) {
738 if (strpos('_', $name) !== false) {
739 continue;
741 if ($mform->elementExists($name)) {
742 $element = $mform->getElement($name);
743 $lockedsetting = $name . '_locked';
744 if (!empty($settings->$lockedsetting)) {
745 // Always lock locked settings for new modules,
746 // for updates, only lock them if the current value is the same as the default (or there is no current value).
747 $value = $settings->$name;
748 if ($isupdate && isset($this->current->$name)) {
749 $value = $this->current->$name;
751 if ($value == $settings->$name) {
752 $mform->setConstant($name, $settings->$name);
753 $element->setLabel($element->getLabel() . $lockedicon);
754 // Do not use hardfreeze because we need the hidden input to check dependencies.
755 $element->freeze();
763 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
765 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
766 * default date/time value should be relative to. If not passed, all
767 * date/time fields are set relative to the users current midnight.
768 * @return void
770 public function apply_admin_defaults($datetimeoffsets = array()) {
771 // This flag triggers the settings to be locked in apply_admin_locked_flags().
772 $this->applyadminlockedflags = true;
774 $settings = get_config($this->_modname);
775 $mform = $this->_form;
776 $usermidnight = usergetmidnight(time());
777 $isupdate = !empty($this->_cm);
779 foreach ($settings as $name => $value) {
780 if (strpos('_', $name) !== false) {
781 continue;
783 if ($mform->elementExists($name)) {
784 $element = $mform->getElement($name);
785 if (!$isupdate) {
786 if ($element->getType() == 'date_time_selector') {
787 $enabledsetting = $name . '_enabled';
788 if (empty($settings->$enabledsetting)) {
789 $mform->setDefault($name, 0);
790 } else {
791 $relativetime = $usermidnight;
792 if (isset($datetimeoffsets[$name])) {
793 $relativetime = $datetimeoffsets[$name];
795 $mform->setDefault($name, $relativetime + $settings->$name);
797 } else {
798 $mform->setDefault($name, $settings->$name);
801 $advancedsetting = $name . '_adv';
802 if (!empty($settings->$advancedsetting)) {
803 $mform->setAdvanced($name);