MDL-37516 Conditional activities: user field condition display fixes
[moodle.git] / course / moodleform_mod.php
blobd9345e31bb87070117d5581e879fa1cb4bf459d9
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 function moodleform_mod($current, $section, $cm, $course) {
53 $this->current = $current;
54 $this->_instance = $current->instance;
55 $this->_section = $section;
56 $this->_cm = $cm;
57 if ($this->_cm) {
58 $this->context = context_module::instance($this->_cm->id);
59 } else {
60 $this->context = context_course::instance($course->id);
63 // Guess module name
64 $matches = array();
65 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
66 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
67 print_error('unknownmodulename');
69 $this->_modname = $matches[1];
70 $this->init_features();
71 parent::moodleform('modedit.php');
74 protected function init_features() {
75 global $CFG;
77 $this->_features = new stdClass();
78 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
79 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
80 $this->_features->groupmembersonly = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
81 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
82 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
83 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
84 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
85 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
86 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
87 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
89 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
90 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
93 /**
94 * Only available on moodleform_mod.
96 * @param array $default_values passed by reference
98 function data_preprocessing(&$default_values){
99 if (empty($default_values['scale'])) {
100 $default_values['assessed'] = 0;
103 if (empty($default_values['assessed'])){
104 $default_values['ratingtime'] = 0;
105 } else {
106 $default_values['ratingtime']=
107 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
112 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
114 function definition_after_data() {
115 global $CFG, $COURSE;
116 $mform =& $this->_form;
118 if ($id = $mform->getElementValue('update')) {
119 $modulename = $mform->getElementValue('modulename');
120 $instance = $mform->getElementValue('instance');
122 if ($this->_features->gradecat) {
123 $gradecat = false;
124 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
125 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
126 if (!empty($outcomes)) {
127 $gradecat = true;
131 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
132 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
133 if (!empty($items)) {
134 foreach ($items as $item) {
135 if (!empty($item->outcomeid)) {
136 $elname = 'outcome_'.$item->outcomeid;
137 if ($mform->elementExists($elname)) {
138 $mform->hardFreeze($elname); // prevent removing of existing outcomes
143 foreach ($items as $item) {
144 if (is_bool($gradecat)) {
145 $gradecat = $item->categoryid;
146 continue;
148 if ($gradecat != $item->categoryid) {
149 //mixed categories
150 $gradecat = false;
151 break;
156 if ($gradecat === false) {
157 // items and outcomes in different categories - remove the option
158 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
159 if ($mform->elementExists('gradecat')) {
160 $mform->removeElement('gradecat');
161 if ($this->_features->rating) {
162 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
163 $mform->removeElement('modstandardgrade');
170 if ($COURSE->groupmodeforce) {
171 if ($mform->elementExists('groupmode')) {
172 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
176 // Don't disable/remove groupingid if it is currently set to something,
177 // otherwise you cannot turn it off at same time as turning off other
178 // option (MDL-30764)
179 if (empty($this->_cm) || !$this->_cm->groupingid) {
180 if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
181 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
183 } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
184 $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
186 } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
187 // groupings have no use without groupmode or groupmembersonly
188 if ($mform->elementExists('groupingid')) {
189 $mform->removeElement('groupingid');
194 // Completion: If necessary, freeze fields
195 $completion = new completion_info($COURSE);
196 if ($completion->is_enabled()) {
197 // If anybody has completed the activity, these options will be 'locked'
198 $completedcount = empty($this->_cm)
200 : $completion->count_user_data($this->_cm);
202 $freeze = false;
203 if (!$completedcount) {
204 if ($mform->elementExists('unlockcompletion')) {
205 $mform->removeElement('unlockcompletion');
207 // Automatically set to unlocked (note: this is necessary
208 // in order to make it recalculate completion once the option
209 // is changed, maybe someone has completed it now)
210 $mform->getElement('completionunlocked')->setValue(1);
211 } else {
212 // Has the element been unlocked?
213 if ($mform->exportValue('unlockcompletion')) {
214 // Yes, add in warning text and set the hidden variable
215 $mform->insertElementBefore(
216 $mform->createElement('static', 'completedunlocked',
217 get_string('completedunlocked', 'completion'),
218 get_string('completedunlockedtext', 'completion')),
219 'unlockcompletion');
220 $mform->removeElement('unlockcompletion');
221 $mform->getElement('completionunlocked')->setValue(1);
222 } else {
223 // No, add in the warning text with the count (now we know
224 // it) before the unlock button
225 $mform->insertElementBefore(
226 $mform->createElement('static', 'completedwarning',
227 get_string('completedwarning', 'completion'),
228 get_string('completedwarningtext', 'completion', $completedcount)),
229 'unlockcompletion');
230 $freeze = true;
234 if ($freeze) {
235 $mform->freeze('completion');
236 if ($mform->elementExists('completionview')) {
237 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
239 if ($mform->elementExists('completionusegrade')) {
240 $mform->freeze('completionusegrade');
242 $mform->freeze($this->_customcompletionelements);
246 // Availability conditions
247 if (!empty($CFG->enableavailability) && $this->_cm) {
248 $ci = new condition_info($this->_cm);
249 $fullcm=$ci->get_full_course_module();
251 $num=0;
252 foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
253 $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
254 $groupelements[0]->setValue($gradeitemid);
255 $groupelements[2]->setValue(is_null($minmax->min) ? '' :
256 format_float($minmax->min, 5, true, true));
257 $groupelements[4]->setValue(is_null($minmax->max) ? '' :
258 format_float($minmax->max, 5, true, true));
259 $num++;
262 $num = 0;
263 foreach($fullcm->conditionsfield as $field => $details) {
264 $groupelements = $mform->getElement('conditionfieldgroup['.$num.']')->getElements();
265 $groupelements[0]->setValue($field);
266 $groupelements[1]->setValue(is_null($details->operator) ? '' : $details->operator);
267 $groupelements[2]->setValue(is_null($details->value) ? '' : $details->value);
268 $num++;
271 if ($completion->is_enabled()) {
272 $num=0;
273 foreach($fullcm->conditionscompletion as $othercmid=>$state) {
274 $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
275 $groupelements[0]->setValue($othercmid);
276 $groupelements[1]->setValue($state);
277 $num++;
283 // form verification
284 function validation($data, $files) {
285 global $COURSE, $DB;
286 $errors = parent::validation($data, $files);
288 $mform =& $this->_form;
290 $errors = array();
292 if ($mform->elementExists('name')) {
293 $name = trim($data['name']);
294 if ($name == '') {
295 $errors['name'] = get_string('required');
299 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
300 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
301 if ($data['coursemodule']) {
302 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
303 } else {
304 $cm = null;
307 if ($mform->elementExists('cmidnumber')) {
308 // verify the idnumber
309 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
310 $errors['cmidnumber'] = get_string('idnumbertaken');
314 // Completion: Don't let them choose automatic completion without turning
315 // on some conditions. Ignore this check when completion settings are
316 // locked, as the options are then disabled.
317 if (array_key_exists('completion', $data) &&
318 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
319 !empty($data['completionunlocked'])) {
320 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
321 !$this->completion_rule_enabled($data)) {
322 $errors['completion'] = get_string('badautocompletion', 'completion');
326 // Conditions: Don't let them set dates which make no sense
327 if (array_key_exists('availablefrom', $data) &&
328 $data['availablefrom'] && $data['availableuntil'] &&
329 $data['availablefrom'] >= $data['availableuntil']) {
330 $errors['availablefrom'] = get_string('badavailabledates', 'condition');
333 // Conditions: Verify that the grade conditions are numbers, and make sense.
334 if (array_key_exists('conditiongradegroup', $data)) {
335 foreach ($data['conditiongradegroup'] as $i => $gradedata) {
336 if ($gradedata['conditiongrademin'] !== '' &&
337 !is_numeric(unformat_float($gradedata['conditiongrademin']))) {
338 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
339 continue;
341 if ($gradedata['conditiongrademax'] !== '' &&
342 !is_numeric(unformat_float($gradedata['conditiongrademax']))) {
343 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
344 continue;
346 if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
347 unformat_float($gradedata['conditiongrademax']) <= unformat_float($gradedata['conditiongrademin'])) {
348 $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
349 continue;
351 if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
352 $gradedata['conditiongradeitemid']) {
353 $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
354 continue;
356 if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
357 !$gradedata['conditiongradeitemid']) {
358 $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
359 continue;
364 // Conditions: Verify that the user profile field has not been declared more than once
365 if (array_key_exists('conditionfieldgroup', $data)) {
366 // Array to store the existing fields
367 $arrcurrentfields = array();
368 // Error message displayed if any condition is declared more than once. We use lang string because
369 // this way we don't actually generate the string unless there is an error.
370 $stralreadydeclaredwarning = new lang_string('fielddeclaredmultipletimes', 'condition');
371 foreach ($data['conditionfieldgroup'] as $i => $fielddata) {
372 if ($fielddata['conditionfield'] == 0) { // Don't need to bother if none is selected
373 continue;
375 if (in_array($fielddata['conditionfield'], $arrcurrentfields)) {
376 $errors["conditionfieldgroup[{$i}]"] = $stralreadydeclaredwarning->out();
378 // Add the field to the array
379 $arrcurrentfields[] = $fielddata['conditionfield'];
383 return $errors;
387 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
388 * form definition (new entry form); this function is used to load in data where values
389 * already exist and data is being edited (edit entry form).
391 * @param mixed $default_values object or array of default values
393 function set_data($default_values) {
394 if (is_object($default_values)) {
395 $default_values = (array)$default_values;
398 $this->data_preprocessing($default_values);
399 parent::set_data($default_values);
403 * Adds all the standard elements to a form to edit the settings for an activity module.
405 function standard_coursemodule_elements(){
406 global $COURSE, $CFG, $DB;
407 $mform =& $this->_form;
409 $this->_outcomesused = false;
410 if ($this->_features->outcomes) {
411 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
412 $this->_outcomesused = true;
413 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
414 foreach($outcomes as $outcome) {
415 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
421 if ($this->_features->rating) {
422 require_once($CFG->dirroot.'/rating/lib.php');
423 $rm = new rating_manager();
425 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
427 $permission=CAP_ALLOW;
428 $rolenamestring = null;
429 if (!empty($this->_cm)) {
430 $context = context_module::instance($this->_cm->id);
432 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
433 $rolenamestring = implode(', ', $rolenames);
434 } else {
435 $rolenamestring = get_string('capabilitychecknotavailable','rating');
437 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
438 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
440 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
441 $mform->setDefault('assessed', 0);
442 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
444 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
445 $mform->disabledIf('scale', 'assessed', 'eq', 0);
447 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
448 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
450 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
451 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
452 $mform->disabledIf('assesstimestart', 'ratingtime');
454 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
455 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
456 $mform->disabledIf('assesstimefinish', 'ratingtime');
459 //doing this here means splitting up the grade related settings on the lesson settings page
460 //$this->standard_grading_coursemodule_elements();
462 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
464 $mform->addElement('modvisible', 'visible', get_string('visible'));
465 if (!empty($this->_cm)) {
466 $context = context_module::instance($this->_cm->id);
467 if (!has_capability('moodle/course:activityvisibility', $context)) {
468 $mform->hardFreeze('visible');
472 if ($this->_features->idnumber) {
473 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
474 $mform->setType('cmidnumber', PARAM_RAW);
475 $mform->addHelpButton('cmidnumber', 'idnumbermod');
478 if ($this->_features->groups) {
479 $options = array(NOGROUPS => get_string('groupsnone'),
480 SEPARATEGROUPS => get_string('groupsseparate'),
481 VISIBLEGROUPS => get_string('groupsvisible'));
482 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
483 $mform->addHelpButton('groupmode', 'groupmode', 'group');
486 if ($this->_features->groupings or $this->_features->groupmembersonly) {
487 //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
488 $options = array();
489 $options[0] = get_string('none');
490 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
491 foreach ($groupings as $grouping) {
492 $options[$grouping->id] = format_string($grouping->name);
495 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
496 $mform->addHelpButton('groupingid', 'grouping', 'group');
499 if ($this->_features->groupmembersonly) {
500 $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
501 $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
504 if (!empty($CFG->enableavailability)) {
505 // String used by conditions
506 $strnone = get_string('none','condition');
507 // Conditional availability
509 // Available from/to defaults to midnight because then the display
510 // will be nicer where it tells users when they can access it (it
511 // shows only the date and not time).
512 $date = usergetdate(time());
513 $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
515 // From/until controls
516 $mform->addElement('header', 'availabilityconditionsheader',
517 get_string('availabilityconditions', 'condition'));
518 $mform->addElement('date_time_selector', 'availablefrom',
519 get_string('availablefrom', 'condition'),
520 array('optional' => true, 'defaulttime' => $midnight));
521 $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
522 $mform->addElement('date_time_selector', 'availableuntil',
523 get_string('availableuntil', 'condition'),
524 array('optional' => true, 'defaulttime' => $midnight));
526 // Conditions based on grades
527 $gradeoptions = array();
528 $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
529 $items = $items ? $items : array();
530 foreach($items as $id=>$item) {
531 // Do not include grades for current item
532 if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
533 && $this->_cm->modname == $item->itemmodule
534 && $item->itemtype == 'mod') {
535 continue;
537 $gradeoptions[$id] = $item->get_name();
539 asort($gradeoptions);
540 $gradeoptions = array(0 => $strnone) + $gradeoptions;
542 $grouparray = array();
543 $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
544 $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
545 $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
546 $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
547 $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
548 $grouparray[] =& $mform->createElement('static', '', '','%');
549 $group = $mform->createElement('group','conditiongradegroup',
550 get_string('gradecondition', 'condition'),$grouparray);
552 // Get version with condition info and store it so we don't ask
553 // twice
554 if(!empty($this->_cm)) {
555 $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
556 $this->_cm = $ci->get_full_course_module();
557 $count = count($this->_cm->conditionsgrade)+1;
558 $fieldcount = count($this->_cm->conditionsfield) + 1;
559 } else {
560 $count = 1;
561 $fieldcount = 1;
564 $this->repeat_elements(array($group), $count, array(
565 'conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW),
566 'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)
567 ), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
568 $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
570 // Conditions based on user fields
571 $operators = condition_info::get_condition_user_field_operators();
572 $useroptions = condition_info::get_condition_user_fields(
573 array('context' => $this->context));
574 asort($useroptions);
576 $useroptions = array(0 => $strnone) + $useroptions;
577 $grouparray = array();
578 $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
579 $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
580 $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
581 $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
583 $this->repeat_elements(array($group), $fieldcount, array(
584 'conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)),
585 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
586 $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
588 // Conditions based on completion
589 $completion = new completion_info($COURSE);
590 if ($completion->is_enabled()) {
591 $completionoptions = array();
592 $modinfo = get_fast_modinfo($COURSE);
593 foreach($modinfo->cms as $id=>$cm) {
594 // Add each course-module if it:
595 // (a) has completion turned on
596 // (b) is not the same as current course-module
597 if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
598 $completionoptions[$id]=$cm->name;
601 asort($completionoptions);
602 $completionoptions = array(0 => $strnone) + $completionoptions;
604 $completionvalues=array(
605 COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
606 COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
607 COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
608 COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
610 $grouparray = array();
611 $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
612 $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
613 $group = $mform->createElement('group','conditioncompletiongroup',
614 get_string('completioncondition', 'condition'),$grouparray);
616 $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
617 $this->repeat_elements(array($group),$count,array(),
618 'conditioncompletionrepeats','conditioncompletionadds',2,
619 get_string('addcompletions','condition'),true);
620 $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
623 // Do we display availability info to students?
624 $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
625 array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
626 CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
627 $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
630 // Conditional activities: completion tracking section
631 if(!isset($completion)) {
632 $completion = new completion_info($COURSE);
634 if ($completion->is_enabled()) {
635 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
637 // Unlock button for if people have completed it (will
638 // be removed in definition_after_data if they haven't)
639 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
640 $mform->registerNoSubmitButton('unlockcompletion');
641 $mform->addElement('hidden', 'completionunlocked', 0);
642 $mform->setType('completionunlocked', PARAM_INT);
644 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
645 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
646 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
647 $mform->setDefault('completion', $this->_features->defaultcompletion
648 ? COMPLETION_TRACKING_MANUAL
649 : COMPLETION_TRACKING_NONE);
650 $mform->addHelpButton('completion', 'completion', 'completion');
652 // Automatic completion once you view it
653 $gotcompletionoptions = false;
654 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
655 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
656 get_string('completionview_desc', 'completion'));
657 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
658 $gotcompletionoptions = true;
661 // Automatic completion once it's graded
662 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
663 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
664 get_string('completionusegrade_desc', 'completion'));
665 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
666 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
667 $gotcompletionoptions = true;
670 // Automatic completion according to module-specific rules
671 $this->_customcompletionelements = $this->add_completion_rules();
672 foreach ($this->_customcompletionelements as $element) {
673 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
676 $gotcompletionoptions = $gotcompletionoptions ||
677 count($this->_customcompletionelements)>0;
679 // Automatic option only appears if possible
680 if ($gotcompletionoptions) {
681 $mform->getElement('completion')->addOption(
682 get_string('completion_automatic', 'completion'),
683 COMPLETION_TRACKING_AUTOMATIC);
686 // Completion expected at particular date? (For progress tracking)
687 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
688 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
689 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
692 $this->standard_hidden_coursemodule_elements();
696 * Can be overridden to add custom completion rules if the module wishes
697 * them. If overriding this, you should also override completion_rule_enabled.
698 * <p>
699 * Just add elements to the form as needed and return the list of IDs. The
700 * system will call disabledIf and handle other behaviour for each returned
701 * ID.
702 * @return array Array of string IDs of added items, empty array if none
704 function add_completion_rules() {
705 return array();
709 * Called during validation. Override to indicate, based on the data, whether
710 * a custom completion rule is enabled (selected).
712 * @param array $data Input data (not yet validated)
713 * @return bool True if one or more rules is enabled, false if none are;
714 * default returns false
716 function completion_rule_enabled($data) {
717 return false;
720 function standard_hidden_coursemodule_elements(){
721 $mform =& $this->_form;
722 $mform->addElement('hidden', 'course', 0);
723 $mform->setType('course', PARAM_INT);
725 $mform->addElement('hidden', 'coursemodule', 0);
726 $mform->setType('coursemodule', PARAM_INT);
728 $mform->addElement('hidden', 'section', 0);
729 $mform->setType('section', PARAM_INT);
731 $mform->addElement('hidden', 'module', 0);
732 $mform->setType('module', PARAM_INT);
734 $mform->addElement('hidden', 'modulename', '');
735 $mform->setType('modulename', PARAM_PLUGIN);
737 $mform->addElement('hidden', 'instance', 0);
738 $mform->setType('instance', PARAM_INT);
740 $mform->addElement('hidden', 'add', 0);
741 $mform->setType('add', PARAM_ALPHA);
743 $mform->addElement('hidden', 'update', 0);
744 $mform->setType('update', PARAM_INT);
746 $mform->addElement('hidden', 'return', 0);
747 $mform->setType('return', PARAM_BOOL);
749 $mform->addElement('hidden', 'sr', 0);
750 $mform->setType('sr', PARAM_INT);
753 public function standard_grading_coursemodule_elements() {
754 global $COURSE, $CFG;
755 $mform =& $this->_form;
757 if ($this->_features->hasgrades) {
759 if (!$this->_features->rating || $this->_features->gradecat) {
760 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
763 //if supports grades and grades arent being handled via ratings
764 if (!$this->_features->rating) {
765 $mform->addElement('modgrade', 'grade', get_string('grade'));
766 $mform->setDefault('grade', 100);
769 if ($this->_features->advancedgrading
770 and !empty($this->current->_advancedgradingdata['methods'])
771 and !empty($this->current->_advancedgradingdata['areas'])) {
773 if (count($this->current->_advancedgradingdata['areas']) == 1) {
774 // if there is just one gradable area (most cases), display just the selector
775 // without its name to make UI simplier
776 $areadata = reset($this->current->_advancedgradingdata['areas']);
777 $areaname = key($this->current->_advancedgradingdata['areas']);
778 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
779 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
780 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
782 } else {
783 // the module defines multiple gradable areas, display a selector
784 // for each of them together with a name of the area
785 $areasgroup = array();
786 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
787 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
788 $areadata['title'], $this->current->_advancedgradingdata['methods']);
789 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
791 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
792 array(' ', '<br />'), false);
796 if ($this->_features->gradecat) {
797 $mform->addElement('select', 'gradecat',
798 get_string('gradecategoryonmodform', 'grades'),
799 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
800 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
805 function add_intro_editor($required=false, $customlabel=null) {
806 if (!$this->_features->introeditor) {
807 // intro editor not supported in this module
808 return;
811 $mform = $this->_form;
812 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
814 $mform->addElement('editor', 'introeditor', $label, array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES,
815 'noclean' => true, 'context' => $this->context, 'collapsed' => true));
816 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
817 if ($required) {
818 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
821 // If the 'show description' feature is enabled, this checkbox appears
822 // below the intro.
823 if ($this->_features->showdescription) {
824 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
825 $mform->addHelpButton('showdescription', 'showdescription');
830 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
832 * @param bool $cancel show cancel button
833 * @param string $submitlabel null means default, false means none, string is label text
834 * @param string $submit2label null means default, false means none, string is label text
835 * @return void
837 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
838 if (is_null($submitlabel)) {
839 $submitlabel = get_string('savechangesanddisplay');
842 if (is_null($submit2label)) {
843 $submit2label = get_string('savechangesandreturntocourse');
846 $mform = $this->_form;
848 // elements in a row need a group
849 $buttonarray = array();
851 if ($submit2label !== false) {
852 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
855 if ($submitlabel !== false) {
856 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
859 if ($cancel) {
860 $buttonarray[] = &$mform->createElement('cancel');
863 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
864 $mform->setType('buttonar', PARAM_RAW);
865 $mform->closeHeaderBefore('buttonar');