protected function add_tag_fields($mform) {
        global $CFG, $DB;

        $hastagcapability = question_has_capability_on($this->question, 'tag');
        // Is the question category in a course context?
        $qcontext = $this->categorycontext;
        $qcoursecontext = $qcontext->get_course_context(false);
        $iscourseoractivityquestion = !empty($qcoursecontext);
        // Is the current context we're editing in a course context?
        $editingcontext = $this->contexts->lowest();
        $editingcoursecontext = $editingcontext->get_course_context(false);
        $iseditingcontextcourseoractivity = !empty($editingcoursecontext);

        $mform->addElement('header', 'tagsheader', get_string('tags'));
        $tags = \core_tag_tag::get_tags_by_area_in_contexts('core_question', 'question', $this->contexts->all());
        $tagstrings = [];
        foreach ($tags as $tag) {
            $tagstrings[$tag->name] = $tag->name;
        }

        $showstandard = core_tag_area::get_showstandard('core_question', 'question');
        if ($showstandard != core_tag_tag::HIDE_STANDARD) {
            $namefield = empty($CFG->keeptagnamecase) ? 'name' : 'rawname';
            $standardtags = $DB->get_records('tag',
                    array('isstandard' => 1, 'tagcollid' => core_tag_area::get_collection('core', 'question')),
                    $namefield, 'id,' . $namefield);
            foreach ($standardtags as $standardtag) {
                $tagstrings[$standardtag->$namefield] = $standardtag->$namefield;
            }
        }

        $options = [
            'tags' => true,
            'multiple' => true,
            'noselectionstring' => get_string('anytags', 'quiz'),
        ];
        $mform->addElement('autocomplete', 'tags',  get_string('tags'), $tagstrings, $options);

        if (!$hastagcapability) {
            $mform->hardFreeze('tags');
        }

        if ($iseditingcontextcourseoractivity && !$iscourseoractivityquestion) {
            // If the question is being edited in a course or activity context
            // and the question isn't a course or activity level question then
            // allow course tags to be added to the course.
            $coursetagheader = get_string('questionformtagheader', 'core_question',
                $editingcoursecontext->get_context_name(true));
            $mform->addElement('header', 'coursetagsheader', $coursetagheader);
            $mform->addElement('autocomplete', 'coursetags',  get_string('tags'), $tagstrings, $options);

            if (!$hastagcapability) {
                $mform->hardFreeze('coursetags');
            }
        }
    }