Add elements to grade form.

@param MoodleQuickForm $mform
@param stdClass $data
@param array $params
@return void
519972
public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
        global $USER, $CFG, $SESSION;
        $settings = $this->get_instance();

        $rownum = isset($params['rownum']) ? $params['rownum'] : 0;
        $last = isset($params['last']) ? $params['last'] : true;
        $useridlistid = isset($params['useridlistid']) ? $params['useridlistid'] : 0;
        $userid = isset($params['userid']) ? $params['userid'] : 0;
        $attemptnumber = isset($params['attemptnumber']) ? $params['attemptnumber'] : 0;
        $gradingpanel = !empty($params['gradingpanel']);
        $bothids = ($userid && $useridlistid);

        if (!$userid || $bothids) {
            $useridlist = $this->get_grading_userid_list(true, $useridlistid);
        } else {
            $useridlist = array($userid);
            $rownum = 0;
            $useridlistid = '';
        }

        $userid = $useridlist[$rownum];
        // We need to create a grade record matching this attempt number
        // or the feedback plugin will have no way to know what is the correct attempt.
        $grade = $this->get_user_grade($userid, true, $attemptnumber);

        $submission = null;
        if ($this->get_instance()->teamsubmission) {
            $submission = $this->get_group_submission($userid, 0, false, $attemptnumber);
        } else {
            $submission = $this->get_user_submission($userid, false, $attemptnumber);
        }

        // Add advanced grading.
        $gradingdisabled = $this->grading_disabled($userid);
        $gradinginstance = $this->get_grading_instance($userid, $grade, $gradingdisabled);

        $mform->addElement('header', 'gradeheader', get_string('grade'));
        if ($gradinginstance) {
            $gradingelement = $mform->addElement('grading',
                                                 'advancedgrading',
                                                 get_string('grade').':',
                                                 array('gradinginstance' => $gradinginstance));
            if ($gradingdisabled) {
                $gradingelement->freeze();
            } else {
                $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
                $mform->setType('advancedgradinginstanceid', PARAM_INT);
            }
        } else {
            // Use simple direct grading.
            if ($this->get_instance()->grade > 0) {
                $name = get_string('gradeoutof', 'assign', $this->get_instance()->grade);
                if (!$gradingdisabled) {
                    $gradingelement = $mform->addElement('text', 'grade', $name);
                    $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
                    $mform->setType('grade', PARAM_RAW);
                } else {
                    $strgradelocked = get_string('gradelocked', 'assign');
                    $mform->addElement('static', 'gradedisabled', $name, $strgradelocked);
                    $mform->addHelpButton('gradedisabled', 'gradeoutofhelp', 'assign');
                }
            } else {
                $grademenu = array(-1 => get_string("nograde")) + make_grades_menu($this->get_instance()->grade);
                if (count($grademenu) > 1) {
                    $gradingelement = $mform->addElement('select', 'grade', get_string('grade') . ':', $grademenu);

                    // The grade is already formatted with format_float so it needs to be converted back to an integer.
                    if (!empty($data->grade)) {
                        $data->grade = (int)unformat_float($data->grade);
                    }
                    $mform->setType('grade', PARAM_INT);
                    if ($gradingdisabled) {
                        $gradingelement->freeze();
                    }
                }
            }
        }

        $gradinginfo = grade_get_grades($this->get_course()->id,
                                        'mod',
                                        'assign',
                                        $this->get_instance()->id,
                                        $userid);
        if (!empty($CFG->enableoutcomes)) {
            foreach ($gradinginfo->outcomes as $index => $outcome) {
                $options = make_grades_menu(-$outcome->scaleid);
                $options[0] = get_string('nooutcome', 'grades');
                if ($outcome->grades[$userid]->locked) {
                    $mform->addElement('static',
                                       'outcome_' . $index . '[' . $userid . ']',
                                       $outcome->name . ':',
                                       $options[$outcome->grades[$userid]->grade]);
                } else {
                    $attributes = array('id' => 'menuoutcome_' . $index );
                    $mform->addElement('select',
                                       'outcome_' . $index . '[' . $userid . ']',
                                       $outcome->name.':',
                                       $options,
                                       $attributes);
                    $mform->setType('outcome_' . $index . '[' . $userid . ']', PARAM_INT);
                    $mform->setDefault('outcome_' . $index . '[' . $userid . ']',
                                       $outcome->grades[$userid]->grade);
                }
            }
        }

        $capabilitylist = array('gradereport/grader:view', 'moodle/grade:viewall');
        if (has_all_capabilities($capabilitylist, $this->get_course_context())) {
            $urlparams = array('id'=>$this->get_course()->id);
            $url = new moodle_url('/grade/report/grader/index.php', $urlparams);
            $usergrade = '-';
            if (isset($gradinginfo->items[0]->grades[$userid]->str_grade)) {
                $usergrade = $gradinginfo->items[0]->grades[$userid]->str_grade;
            }
            $gradestring = $this->get_renderer()->action_link($url, $usergrade);
        } else {
            $usergrade = '-';
            if (isset($gradinginfo->items[0]->grades[$userid]) &&
                    !$gradinginfo->items[0]->grades[$userid]->hidden) {
                $usergrade = $gradinginfo->items[0]->grades[$userid]->str_grade;
            }
            $gradestring = $usergrade;
        }

        if ($this->get_instance()->markingworkflow) {
            $states = $this->get_marking_workflow_states_for_current_user();
            $options = array('' => get_string('markingworkflowstatenotmarked', 'assign')) + $states;
            $mform->addElement('select', 'workflowstate', get_string('markingworkflowstate', 'assign'), $options);
            $mform->addHelpButton('workflowstate', 'markingworkflowstate', 'assign');
        }

        if ($this->get_instance()->markingworkflow &&
            $this->get_instance()->markingallocation &&
            has_capability('mod/assign:manageallocations', $this->context)) {

            list($sort, $params) = users_order_by_sql('u');
            // Only enrolled users could be assigned as potential markers.
            $markers = get_enrolled_users($this->context, 'mod/assign:grade', 0, 'u.*', $sort);
            $markerlist = array('' =>  get_string('choosemarker', 'assign'));
            $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
            foreach ($markers as $marker) {
                $markerlist[$marker->id] = fullname($marker, $viewfullnames);
            }
            $mform->addElement('select', 'allocatedmarker', get_string('allocatedmarker', 'assign'), $markerlist);
            $mform->addHelpButton('allocatedmarker', 'allocatedmarker', 'assign');
            $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW);
            $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW);
            $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE);
            $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
        }
        $gradestring = '<span class="currentgrade">' . $gradestring . '</span>';
        $mform->addElement('static', 'currentgrade', get_string('currentgrade', 'assign'), $gradestring);

        if (count($useridlist) > 1) {
            $strparams = array('current'=>$rownum+1, 'total'=>count($useridlist));
            $name = get_string('outof', 'assign', $strparams);
            $mform->addElement('static', 'gradingstudent', get_string('gradingstudent', 'assign'), $name);
        }

        // Let feedback plugins add elements to the grading form.
        $this->add_plugin_grade_elements($grade, $mform, $data, $userid);

        // Hidden params.
        $mform->addElement('hidden', 'id', $this->get_course_module()->id);
        $mform->setType('id', PARAM_INT);
        $mform->addElement('hidden', 'rownum', $rownum);
        $mform->setType('rownum', PARAM_INT);
        $mform->setConstant('rownum', $rownum);
        $mform->addElement('hidden', 'useridlistid', $useridlistid);
        $mform->setType('useridlistid', PARAM_ALPHANUM);
        $mform->addElement('hidden', 'attemptnumber', $attemptnumber);
        $mform->setType('attemptnumber', PARAM_INT);
        $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
        $mform->setType('ajax', PARAM_INT);
        $mform->addElement('hidden', 'userid', optional_param('userid', 0, PARAM_INT));
        $mform->setType('userid', PARAM_INT);

        if ($this->get_instance()->teamsubmission) {
            $mform->addElement('header', 'groupsubmissionsettings', get_string('groupsubmissionsettings', 'assign'));
            $mform->addElement('selectyesno', 'applytoall', get_string('applytoteam', 'assign'));
            $mform->setDefault('applytoall', 1);
        }

        // Do not show if we are editing a previous attempt.
        if (($attemptnumber == -1 ||
            ($attemptnumber + 1) == count($this->get_all_submissions($userid))) &&
            $this->get_instance()->attemptreopenmethod != ASSIGN_ATTEMPT_REOPEN_METHOD_NONE) {
            $mform->addElement('header', 'attemptsettings', get_string('attemptsettings', 'assign'));
            $attemptreopenmethod = get_string('attemptreopenmethod_' . $this->get_instance()->attemptreopenmethod, 'assign');
            $mform->addElement('static', 'attemptreopenmethod', get_string('attemptreopenmethod', 'assign'), $attemptreopenmethod);

            $attemptnumber = 0;
            if ($submission) {
                $attemptnumber = $submission->attemptnumber;
            }
            $maxattempts = $this->get_instance()->maxattempts;
            if ($maxattempts == ASSIGN_UNLIMITED_ATTEMPTS) {
                $maxattempts = get_string('unlimitedattempts', 'assign');
            }
            $mform->addelement('static', 'maxattemptslabel', get_string('maxattempts', 'assign'), $maxattempts);
            $mform->addelement('static', 'attemptnumberlabel', get_string('attemptnumber', 'assign'), $attemptnumber + 1);

            $ismanual = $this->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL;
            $issubmission = !empty($submission);
            $isunlimited = $this->get_instance()->maxattempts == ASSIGN_UNLIMITED_ATTEMPTS;
            $islessthanmaxattempts = $issubmission && ($submission->attemptnumber < ($this->get_instance()->maxattempts-1));

            if ($ismanual && (!$issubmission || $isunlimited || $islessthanmaxattempts)) {
                $mform->addElement('selectyesno', 'addattempt', get_string('addattempt', 'assign'));
                $mform->setDefault('addattempt', 0);
            }
        }
        if (!$gradingpanel) {
            $mform->addElement('selectyesno', 'sendstudentnotifications', get_string('sendstudentnotifications', 'assign'));
        } else {
            $mform->addElement('hidden', 'sendstudentnotifications', get_string('sendstudentnotifications', 'assign'));
            $mform->setType('sendstudentnotifications', PARAM_BOOL);
        }
        // Get assignment visibility information for student.
        $modinfo = get_fast_modinfo($settings->course, $userid);
        $cm = $modinfo->get_cm($this->get_course_module()->id);

        // Don't allow notification to be sent if the student can't access the assignment,
        // or until in "Released" state if using marking workflow.
        if (!$cm->uservisible) {
            $mform->setDefault('sendstudentnotifications', 0);
            $mform->freeze('sendstudentnotifications');
        } else if ($this->get_instance()->markingworkflow) {
            $mform->setDefault('sendstudentnotifications', 0);
            if (!$gradingpanel) {
                $mform->disabledIf('sendstudentnotifications', 'workflowstate', 'neq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
            }
        } else {
            $mform->setDefault('sendstudentnotifications', $this->get_instance()->sendstudentnotifications);
        }

        $mform->addElement('hidden', 'action', 'submitgrade');
        $mform->setType('action', PARAM_ALPHA);

        if (!$gradingpanel) {

            $buttonarray = array();
            $name = get_string('savechanges', 'assign');
            $buttonarray[] = $mform->createElement('submit', 'savegrade', $name);
            if (!$last) {
                $name = get_string('savenext', 'assign');
                $buttonarray[] = $mform->createElement('submit', 'saveandshownext', $name);
            }
            $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
            $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
            $mform->closeHeaderBefore('buttonar');
            $buttonarray = array();

            if ($rownum > 0) {
                $name = get_string('previous', 'assign');
                $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', $name);
            }

            if (!$last) {
                $name = get_string('nosavebutnext', 'assign');
                $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', $name);
            }
            if (!empty($buttonarray)) {
                $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
            }
        }
        // The grading form does not work well with shortforms.
        $mform->setDisableShortforms();
    }
666378
function definition_after_data() {
        global $CFG, $COURSE;
        $mform =& $this->_form;

        if ($id = $mform->getElementValue('update')) {
            $modulename = $mform->getElementValue('modulename');
            $instance   = $mform->getElementValue('instance');

            if ($this->_features->gradecat) {
                $gradecat = false;
                if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
                    $outcomes = grade_outcome::fetch_all_available($COURSE->id);
                    if (!empty($outcomes)) {
                        $gradecat = true;
                    }
                }

                $hasgradeitems = false;
                $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
                //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
                if (!empty($items)) {
                    foreach ($items as $item) {
                        if (!empty($item->outcomeid)) {
                            $elname = 'outcome_'.$item->outcomeid;
                            if ($mform->elementExists($elname)) {
                                $mform->hardFreeze($elname); // prevent removing of existing outcomes
                            }
                        } else {
                            $hasgradeitems = true;
                        }
                    }

                    foreach ($items as $item) {
                        if (is_bool($gradecat)) {
                            $gradecat = $item->categoryid;
                            continue;
                        }
                        if ($gradecat != $item->categoryid) {
                            //mixed categories
                            $gradecat = false;
                            break;
                        }
                    }
                }

                if (!$hasgradeitems && $mform->elementExists('gradepass')) {
                    // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
                    $mform->removeElement('gradepass');
                }

                if ($gradecat === false) {
                    // items and outcomes in different categories - remove the option
                    // TODO: add a "Mixed categories" text instead of removing elements with no explanation
                    if ($mform->elementExists('gradecat')) {
                        $mform->removeElement('gradecat');
                        if ($this->_features->rating  && !$mform->elementExists('gradepass')) {
                            //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
                            $mform->removeElement('modstandardgrade');
                        }
                    }
                }
            }
        }

        if ($COURSE->groupmodeforce) {
            if ($mform->elementExists('groupmode')) {
                $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
            }
        }

        // Don't disable/remove groupingid if it is currently set to something,
        // otherwise you cannot turn it off at same time as turning off other
        // option (MDL-30764)
        if (empty($this->_cm) || !$this->_cm->groupingid) {
            if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
                $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS);

            } else if (!$mform->elementExists('groupmode')) {
                // Groupings have no use without groupmode.
                if ($mform->elementExists('groupingid')) {
                    $mform->removeElement('groupingid');
                }
                // Nor does the group restrictions button.
                if ($mform->elementExists('restrictgroupbutton')) {
                    $mform->removeElement('restrictgroupbutton');
                }
            }
        }

        // Completion: If necessary, freeze fields
        $completion = new completion_info($COURSE);
        if ($completion->is_enabled()) {
            // If anybody has completed the activity, these options will be 'locked'
            $completedcount = empty($this->_cm)
                ? 0
                : $completion->count_user_data($this->_cm);

            $freeze = false;
            if (!$completedcount) {
                if ($mform->elementExists('unlockcompletion')) {
                    $mform->removeElement('unlockcompletion');
                }
                // Automatically set to unlocked (note: this is necessary
                // in order to make it recalculate completion once the option
                // is changed, maybe someone has completed it now)
                $mform->getElement('completionunlocked')->setValue(1);
            } else {
                // Has the element been unlocked, either by the button being pressed
                // in this request, or the field already being set from a previous one?
                if ($mform->exportValue('unlockcompletion') ||
                        $mform->exportValue('completionunlocked')) {
                    // Yes, add in warning text and set the hidden variable
                    $mform->insertElementBefore(
                        $mform->createElement('static', 'completedunlocked',
                            get_string('completedunlocked', 'completion'),
                            get_string('completedunlockedtext', 'completion')),
                        'unlockcompletion');
                    $mform->removeElement('unlockcompletion');
                    $mform->getElement('completionunlocked')->setValue(1);
                } else {
                    // No, add in the warning text with the count (now we know
                    // it) before the unlock button
                    $mform->insertElementBefore(
                        $mform->createElement('static', 'completedwarning',
                            get_string('completedwarning', 'completion'),
                            get_string('completedwarningtext', 'completion', $completedcount)),
                        'unlockcompletion');
                    $freeze = true;
                }
            }

            if ($freeze) {
                $mform->freeze('completion');
                if ($mform->elementExists('completionview')) {
                    $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
                }
                if ($mform->elementExists('completionusegrade')) {
                    $mform->freeze('completionusegrade');
                }
                $mform->freeze($this->_customcompletionelements);
            }
        }

        // Freeze admin defaults if required (and not different from default)
        $this->apply_admin_locked_flags();
    }
1246368
protected function add_config_field_to_form(\MoodleQuickForm &$mform, $key) {
        $options = [
            true    => get_string('yes'),
            false   => get_string('no'),
        ];
        $mform->addElement('select', $key, get_string($key, 'tool_usertours'), $options);
        $mform->setDefault($key, configuration::get_default_value($key));
        $mform->addHelpButton($key, $key, 'tool_usertours');

        return $this;
    }
900529
protected function process_grading_batch_operation(& $mform) {
        global $CFG;
        require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
        require_sesskey();

        $markingallocation = $this->get_instance()->markingworkflow &&
            $this->get_instance()->markingallocation &&
            has_capability('mod/assign:manageallocations', $this->context);

        $batchformparams = array('cm'=>$this->get_course_module()->id,
                                 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
                                 'duedate'=>$this->get_instance()->duedate,
                                 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
                                 'feedbackplugins'=>$this->get_feedback_plugins(),
                                 'context'=>$this->get_context(),
                                 'markingworkflow'=>$this->get_instance()->markingworkflow,
                                 'markingallocation'=>$markingallocation);
        $formclasses = array('class'=>'gradingbatchoperationsform');
        $mform = new mod_assign_grading_batch_operations_form(null,
                                                              $batchformparams,
                                                              'post',
                                                              '',
                                                              $formclasses);

        if ($data = $mform->get_data()) {
            // Get the list of users.
            $users = $data->selectedusers;
            $userlist = explode(',', $users);

            $prefix = 'plugingradingbatchoperation_';

            if ($data->operation == 'grantextension') {
                // Reset the form so the grant extension page will create the extension form.
                $mform = null;
                return 'grantextension';
            } else if ($data->operation == 'setmarkingworkflowstate') {
                return 'viewbatchsetmarkingworkflowstate';
            } else if ($data->operation == 'setmarkingallocation') {
                return 'viewbatchmarkingallocation';
            } else if (strpos($data->operation, $prefix) === 0) {
                $tail = substr($data->operation, strlen($prefix));
                list($plugintype, $action) = explode('_', $tail, 2);

                $plugin = $this->get_feedback_plugin_by_type($plugintype);
                if ($plugin) {
                    return 'plugingradingbatchoperation';
                }
            }

            if ($data->operation == 'downloadselected') {
                $this->download_submissions($userlist);
            } else {
                foreach ($userlist as $userid) {
                    if ($data->operation == 'lock') {
                        $this->process_lock_submission($userid);
                    } else if ($data->operation == 'unlock') {
                        $this->process_unlock_submission($userid);
                    } else if ($data->operation == 'reverttodraft') {
                        $this->process_revert_to_draft($userid);
                    } else if ($data->operation == 'removesubmission') {
                        $this->process_remove_submission($userid);
                    } else if ($data->operation == 'addattempt') {
                        if (!$this->get_instance()->teamsubmission) {
                            $this->process_add_attempt($userid);
                        }
                    }
                }
            }
            if ($this->get_instance()->teamsubmission && $data->operation == 'addattempt') {
                // This needs to be handled separately so that each team submission is only re-opened one time.
                $this->process_add_attempt_group($userlist);
            }
        }

        return 'grading';
    }
455267
protected function view_grant_extension($mform) {
        global $CFG;
        require_once($CFG->dirroot . '/mod/assign/extensionform.php');

        $o = '';

        $data = new stdClass();
        $data->id = $this->get_course_module()->id;

        $formparams = array(
            'instance' => $this->get_instance(),
            'assign' => $this
        );

        $users = optional_param('userid', 0, PARAM_INT);
        if (!$users) {
            $users = required_param('selectedusers', PARAM_SEQUENCE);
        }
        $userlist = explode(',', $users);

        $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
        $maxoverride = array('allowsubmissionsfromdate' => 0, 'duedate' => 0, 'cutoffdate' => 0);
        foreach ($userlist as $userid) {
            // To validate extension date with users overrides.
            $override = $this->override_exists($userid);
            foreach ($keys as $key) {
                if ($override->{$key}) {
                    if ($maxoverride[$key] < $override->{$key}) {
                        $maxoverride[$key] = $override->{$key};
                    }
                } else if ($maxoverride[$key] < $this->get_instance()->{$key}) {
                    $maxoverride[$key] = $this->get_instance()->{$key};
                }
            }
        }
        foreach ($keys as $key) {
            if ($maxoverride[$key]) {
                $this->get_instance()->{$key} = $maxoverride[$key];
            }
        }

        $formparams['userlist'] = $userlist;

        $data->selectedusers = $users;
        $data->userid = 0;

        if (empty($mform)) {
            $mform = new mod_assign_extension_form(null, $formparams);
        }
        $mform->set_data($data);
        $header = new assign_header($this->get_instance(),
                                    $this->get_context(),
                                    $this->show_intro(),
                                    $this->get_course_module()->id,
                                    get_string('grantextension', 'assign'));
        $o .= $this->get_renderer()->render($header);
        $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
        $o .= $this->view_footer();
        return $o;
    }
1005269
public function instance_form_definition(\MoodleQuickForm $mform) {
        $field = $this->get_field();
        // Get the current calendar in use - see MDL-18375.
        $calendartype = \core_calendar\type_factory::get_calendar_instance();

        $config = $field->get('configdata');

        // Always set the form element to "optional", even when it's required. Otherwise it defaults to the
        // current date and is easy to miss.
        $attributes = ['optional' => true];

        if (!empty($config['mindate'])) {
            $attributes['startyear'] = $calendartype->timestamp_to_date_array($config['mindate'])['year'];
        }

        if (!empty($config['maxdate'])) {
            $attributes['stopyear'] = $calendartype->timestamp_to_date_array($config['maxdate'])['year'];
        }

        if (empty($config['includetime'])) {
            $element = 'date_selector';
        } else {
            $element = 'date_time_selector';
        }
        $elementname = $this->get_form_element_name();
        $mform->addElement($element, $elementname, $this->get_field()->get_formatted_name(), $attributes);
        $mform->setType($elementname, PARAM_INT);
        $mform->setDefault($elementname, time());
        if ($field->get_configdata_property('required')) {
            $mform->addRule($elementname, null, 'required', null, 'client');
        }
    }
1046711
public function edit_field_add($mform) {
        $mform->addElement('select', $this->inputname, format_string($this->field->name), $this->options);
    }
976060
public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
        global $DB;

        $nameattribs = array('size' => '20', 'maxlength' => '255');
        $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
        $mform->setType('name', PARAM_TEXT);
        $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');

        $tools = array();
        $tools[$context->id] = get_string('course');
        $modinfo = get_fast_modinfo($instance->courseid);
        $mods = $modinfo->get_cms();
        foreach ($mods as $mod) {
            $tools[$mod->context->id] = format_string($mod->name);
        }

        $mform->addElement('select', 'contextid', get_string('tooltobeprovided', 'enrol_lti'), $tools);
        $mform->setDefault('contextid', $context->id);

        $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_lti'),
            array('optional' => true, 'defaultunit' => DAYSECS));
        $mform->setDefault('enrolperiod', 0);
        $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_lti');

        $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_lti'),
            array('optional' => true));
        $mform->setDefault('enrolstartdate', 0);
        $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_lti');

        $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_lti'),
            array('optional' => true));
        $mform->setDefault('enrolenddate', 0);
        $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_lti');

        $mform->addElement('text', 'maxenrolled', get_string('maxenrolled', 'enrol_lti'));
        $mform->setDefault('maxenrolled', 0);
        $mform->addHelpButton('maxenrolled', 'maxenrolled', 'enrol_lti');
        $mform->setType('maxenrolled', PARAM_INT);

        $assignableroles = get_assignable_roles($context);

        $mform->addElement('select', 'roleinstructor', get_string('roleinstructor', 'enrol_lti'), $assignableroles);
        $mform->setDefault('roleinstructor', '3');
        $mform->addHelpButton('roleinstructor', 'roleinstructor', 'enrol_lti');

        $mform->addElement('select', 'rolelearner', get_string('rolelearner', 'enrol_lti'), $assignableroles);
        $mform->setDefault('rolelearner', '5');
        $mform->addHelpButton('rolelearner', 'rolelearner', 'enrol_lti');

        $mform->addElement('header', 'remotesystem', get_string('remotesystem', 'enrol_lti'));

        $mform->addElement('text', 'secret', get_string('secret', 'enrol_lti'), 'maxlength="64" size="25"');
        $mform->setType('secret', PARAM_ALPHANUM);
        $mform->setDefault('secret', random_string(32));
        $mform->addHelpButton('secret', 'secret', 'enrol_lti');
        $mform->addRule('secret', get_string('required'), 'required');

        $mform->addElement('selectyesno', 'gradesync', get_string('gradesync', 'enrol_lti'));
        $mform->setDefault('gradesync', 1);
        $mform->addHelpButton('gradesync', 'gradesync', 'enrol_lti');

        $mform->addElement('selectyesno', 'gradesynccompletion', get_string('requirecompletion', 'enrol_lti'));
        $mform->setDefault('gradesynccompletion', 0);
        $mform->disabledIf('gradesynccompletion', 'gradesync', 0);

        $mform->addElement('selectyesno', 'membersync', get_string('membersync', 'enrol_lti'));
        $mform->setDefault('membersync', 1);
        $mform->addHelpButton('membersync', 'membersync', 'enrol_lti');

        $options = array();
        $options[\enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL] = get_string('membersyncmodeenrolandunenrol', 'enrol_lti');
        $options[\enrol_lti\helper::MEMBER_SYNC_ENROL_NEW] = get_string('membersyncmodeenrolnew', 'enrol_lti');
        $options[\enrol_lti\helper::MEMBER_SYNC_UNENROL_MISSING] = get_string('membersyncmodeunenrolmissing', 'enrol_lti');
        $mform->addElement('select', 'membersyncmode', get_string('membersyncmode', 'enrol_lti'), $options);
        $mform->setDefault('membersyncmode', \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL);
        $mform->addHelpButton('membersyncmode', 'membersyncmode', 'enrol_lti');
        $mform->disabledIf('membersyncmode', 'membersync', 0);

        $mform->addElement('header', 'defaultheader', get_string('userdefaultvalues', 'enrol_lti'));

        $emaildisplay = get_config('enrol_lti', 'emaildisplay');
        $choices = array(
            0 => get_string('emaildisplayno'),
            1 => get_string('emaildisplayyes'),
            2 => get_string('emaildisplaycourse')
        );
        $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
        $mform->setDefault('maildisplay', $emaildisplay);
        $mform->addHelpButton('maildisplay', 'emaildisplay');

        $city = get_config('enrol_lti', 'city');
        $mform->addElement('text', 'city', get_string('city'), 'maxlength="100" size="25"');
        $mform->setType('city', PARAM_TEXT);
        $mform->setDefault('city', $city);

        $country = get_config('enrol_lti', 'country');
        $countries = array('' => get_string('selectacountry') . '...') + get_string_manager()->get_list_of_countries();
        $mform->addElement('select', 'country', get_string('selectacountry'), $countries);
        $mform->setDefault('country', $country);
        $mform->setAdvanced('country');

        $timezone = get_config('enrol_lti', 'timezone');
        $choices = core_date::get_list_of_timezones(null, true);
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
        $mform->setDefault('timezone', $timezone);
        $mform->setAdvanced('timezone');

        $lang = get_config('enrol_lti', 'lang');
        $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
        $mform->setDefault('lang', $lang);
        $mform->setAdvanced('lang');

        $institution = get_config('enrol_lti', 'institution');
        $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"');
        $mform->setType('institution', core_user::get_property_type('institution'));
        $mform->setDefault('institution', $institution);
        $mform->setAdvanced('institution');

        // Check if we are editing an instance.
        if (!empty($instance->id)) {
            // Get the details from the enrol_lti_tools table.
            $ltitool = $DB->get_record('enrol_lti_tools', array('enrolid' => $instance->id), '*', MUST_EXIST);

            $mform->addElement('hidden', 'toolid');
            $mform->setType('toolid', PARAM_INT);
            $mform->setConstant('toolid', $ltitool->id);

            $mform->setDefaults((array) $ltitool);
        }
    }
885624
public function get_form_elements_for_user($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
        $commentinlinenabled = $this->get_config('commentinline');
        $submission = $this->assignment->get_user_submission($userid, false);
        $feedbackcomments = false;

        if ($grade) {
            $feedbackcomments = $this->get_feedback_comments($grade->id);
        }

        if ($feedbackcomments && !empty($feedbackcomments->commenttext)) {
            $data->assignfeedbackcomments = $feedbackcomments->commenttext;
            $data->assignfeedbackcommentsformat = $feedbackcomments->commentformat;
        } else {
            // No feedback given yet - maybe we need to copy the text from the submission?
            if (!empty($commentinlinenabled) && $submission) {
                $this->convert_submission_text_to_feedback($submission, $data, $grade);
            } else { // Set it to empty.
                $data->assignfeedbackcomments = '';
                $data->assignfeedbackcommentsformat = FORMAT_HTML;
            }
        }

        file_prepare_standard_editor(
            $data,
            'assignfeedbackcomments',
            $this->get_editor_options(),
            $this->assignment->get_context(),
            ASSIGNFEEDBACK_COMMENTS_COMPONENT,
            ASSIGNFEEDBACK_COMMENTS_FILEAREA,
            $grade->id
        );

        $mform->addElement('editor', 'assignfeedbackcomments_editor', $this->get_name(), null, $this->get_editor_options());

        return true;
    }
153946
protected function check_submit_for_grading($mform) {
        global $USER, $CFG;

        require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');

        // Check that all of the submission plugins are ready for this submission.
        $notifications = array();
        $submission = $this->get_user_submission($USER->id, false);
        $plugins = $this->get_submission_plugins();
        foreach ($plugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                $check = $plugin->precheck_submission($submission);
                if ($check !== true) {
                    $notifications[] = $check;
                }
            }
        }

        $data = new stdClass();
        $adminconfig = $this->get_admin_config();
        $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement;
        $submissionstatement = '';

        if ($requiresubmissionstatement) {
            $submissionstatement = $this->get_submissionstatement($adminconfig, $this->get_instance(), $this->get_context());
        }

        // If we get back an empty submission statement, we have to set $requiredsubmisisonstatement to false to prevent
        // that the submission statement checkbox will be displayed.
        if (empty($submissionstatement)) {
            $requiresubmissionstatement = false;
        }

        if ($mform == null) {
            $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
                                                                        $submissionstatement,
                                                                        $this->get_course_module()->id,
                                                                        $data));
        }
        $o = '';
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                              $this->get_context(),
                                                              $this->show_intro(),
                                                              $this->get_course_module()->id,
                                                              get_string('confirmsubmissionheading', 'assign')));
        $submitforgradingpage = new assign_submit_for_grading_page($notifications,
                                                                   $this->get_course_module()->id,
                                                                   $mform);
        $o .= $this->get_renderer()->render($submitforgradingpage);
        $o .= $this->view_footer();

        \mod_assign\event\submission_confirmation_form_viewed::create_from_assign($this)->trigger();

        return $o;
    }
786571
public function config_form_display(&$mform, $data = null) {

        $mform->addElement('checkbox', 'criteria_duration', get_string('enable'));

        // Populate the duration length drop down.
        $thresholdmenu = array(
            // We have strings for 1 - 6 days in the core.
            86400 => get_string('secondstotime86400', 'core'),
            172800 => get_string('secondstotime172800', 'core'),
            259200 => get_string('secondstotime259200', 'core'),
            345600 => get_string('secondstotime345600', 'core'),
            432000 => get_string('secondstotime432000', 'core'),
            518400 => get_string('secondstotime518400', 'core'),
            518400 => get_string('secondstotime518400', 'core'),
        );
        // Append strings for 7 - 30 days (step by 1 day).
        for ($i = 7; $i <= 30; $i++) {
            $seconds = $i * DAYSECS;
            $thresholdmenu[$seconds] = get_string('numdays', 'core', $i);
        }
        // Append strings for 40 - 180 days (step by 10 days).
        for ($i = 40; $i <= 180; $i = $i + 10) {
            $seconds = $i * DAYSECS;
            $thresholdmenu[$seconds] = get_string('numdays', 'core', $i);
        }
        // Append string for 1 year.
        $thresholdmenu[365 * DAYSECS] = get_string('numdays', 'core', 365);

        $mform->addElement('select', 'criteria_duration_days', get_string('enrolmentdurationlength', 'core_completion'), $thresholdmenu);
        $mform->disabledIf('criteria_duration_days', 'criteria_duration');

        if ($this->id) {
            $mform->setDefault('criteria_duration', 1);
            $mform->setDefault('criteria_duration_days', $this->enrolperiod);
        }
    }
1075530
protected function add_default_hidden_elements($mform) {
        global $USER;

        // Add some hidden fields.
        $mform->addElement('hidden', 'id');
        $mform->setType('id', PARAM_INT);
        $mform->setDefault('id', 0);

        $mform->addElement('hidden', 'userid');
        $mform->setType('userid', PARAM_INT);
        $mform->setDefault('userid', $USER->id);

        $mform->addElement('hidden', 'modulename');
        $mform->setType('modulename', PARAM_INT);
        $mform->setDefault('modulename', '');

        $mform->addElement('hidden', 'instance');
        $mform->setType('instance', PARAM_INT);
        $mform->setDefault('instance', 0);

        $mform->addElement('hidden', 'visible');
        $mform->setType('visible', PARAM_INT);
        $mform->setDefault('visible', 1);
    }
1184288
public function config_form_display(&$mform, $data = null) {
        $mform->addElement('checkbox', 'criteria_date', get_string('enable'));
        $mform->addElement('date_selector', 'criteria_date_value', get_string('completionondatevalue', 'core_completion'));
        $mform->disabledIf('criteria_date_value', 'criteria_date');

        // If instance of criteria exists
        if ($this->id) {
            $mform->setDefault('criteria_date', 1);
            $mform->setDefault('criteria_date_value', $this->timeend);
        } else {
            $mform->setDefault('criteria_date_value', time() + 3600 * 24);
        }
    }
801576
public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
        global $CFG;

        // Merge these two settings to one value for the single selection element.
        if ($instance->notifyall and $instance->expirynotify) {
            $instance->expirynotify = 2;
        }
        unset($instance->notifyall);

        $nameattribs = array('size' => '20', 'maxlength' => '255');
        $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
        $mform->setType('name', PARAM_TEXT);
        $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');

        $options = $this->get_status_options();
        $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
        $mform->addHelpButton('status', 'status', 'enrol_self');

        $options = $this->get_newenrols_options();
        $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
        $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
        $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED);

        $passattribs = array('size' => '20', 'maxlength' => '50');
        $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
        $mform->addHelpButton('password', 'password', 'enrol_self');
        if (empty($instance->id) and $this->get_config('requirepassword')) {
            $mform->addRule('password', get_string('required'), 'required', null, 'client');
        }
        $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');

        $options = $this->get_groupkey_options();
        $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
        $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');

        $roles = $this->extend_assignable_roles($context, $instance->roleid);
        $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);

        $options = array('optional' => true, 'defaultunit' => 86400);
        $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
        $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');

        $options = $this->get_expirynotify_options();
        $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
        $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');

        $options = array('optional' => false, 'defaultunit' => 86400);
        $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
        $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
        $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);

        $options = array('optional' => true);
        $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
        $mform->setDefault('enrolstartdate', 0);
        $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');

        $options = array('optional' => true);
        $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
        $mform->setDefault('enrolenddate', 0);
        $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');

        $options = $this->get_longtimenosee_options();
        $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
        $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');

        $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
        $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
        $mform->setType('customint3', PARAM_INT);

        require_once($CFG->dirroot.'/cohort/lib.php');

        $cohorts = array(0 => get_string('no'));
        $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
        if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
            $c = $DB->get_record('cohort',
                                 array('id' => $instance->customint5),
                                 'id, name, idnumber, contextid, visible',
                                 IGNORE_MISSING);
            if ($c) {
                // Current cohort was not found because current user can not see it. Still keep it.
                $allcohorts[$instance->customint5] = $c;
            }
        }
        foreach ($allcohorts as $c) {
            $cohorts[$c->id] = format_string($c->name, true, array('context' => context::instance_by_id($c->contextid)));
            if ($c->idnumber) {
                $cohorts[$c->id] .= ' ['.s($c->idnumber).']';
            }
        }
        if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
            // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
            $cohorts[$instance->customint5] = get_string('unknowncohort', 'cohort', $instance->customint5);
        }
        if (count($cohorts) > 1) {
            $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
            $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
        } else {
            $mform->addElement('hidden', 'customint5');
            $mform->setType('customint5', PARAM_INT);
            $mform->setConstant('customint5', 0);
        }

        $mform->addElement('select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'),
                enrol_send_welcome_email_options());
        $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');

        $options = array('cols' => '60', 'rows' => '8');
        $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
        $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');

        if (enrol_accessing_via_instance($instance)) {
            $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
            $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
        }
    }
650128
public function instance_form_definition(\MoodleQuickForm $mform) {
        $field = $this->get_field();
        $desceditoroptions = $this->value_editor_options();
        $elementname = $this->get_form_element_name();
        $mform->addElement('editor', $elementname, $this->get_field()->get_formatted_name(), null, $desceditoroptions);
        if ($field->get_configdata_property('required')) {
            $mform->addRule($elementname, null, 'required', null, 'client');
        }
    }
1321462
protected function add_plugin_submission_elements($submission,
                                                    MoodleQuickForm $mform,
                                                    stdClass $data,
                                                    $userid) {
        foreach ($this->submissionplugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
                $plugin->get_form_elements_for_user($submission, $mform, $data, $userid);
            }
        }
    }
186572
public function process_gradinform_guide_filling($data) {
        global $DB;

        $data = (object)$data;
        $data->instanceid = $this->get_new_parentid('grading_instance');
        $data->criterionid = $this->get_mappingid('gradingform_guide_criterion', $data->criterionid);

        $DB->insert_record('gradingform_guide_fillings', $data);
    }