Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Course Custom fields

From MoodleDocs
Revision as of 11:36, 25 October 2021 by Benjamin Ellis (talk | contribs) (Initial Edit of this page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Introduction

This plugin type allows you to add course custom field types of which instances can be added to a course. For example, if you want to display radio buttons on the course edit page, then create a radio custom course field plugin, then create an instance of it.

Default Custom Fields

Moodle supports five default course custom fields field plugins:

  1. checkbox
  2. datetime
  3. menu
  4. text
  5. textarea

Required Files

  • version.php
  • language file e.g lang/en/customfield_radio.php
  • classes/data_controller.php
  • classes/field_controller.php

The Class Files

The two required files in the classes folder must follow the autoloading and namespacing rules e.g. customfield_radio.

Field Controller

Data Controller

The data controller is the class that deals with the UI in the course edit form. It must be called data_controller (for autoloading) and must extend the \core_customfield\data_controller class. It must override the following methods:

datafield()

Should return the name of the field in the db table {customfield_data} where the data is stored and must be one of the following:

  • intvalue - can store integer values, this field is indexed
  • decvalue - can store decimal values
  • shortcharvalue - can store character values up to 255 characters long, this field is indexed
  • charvalue - can store character values up to 1333 characters long, this field is not indexed
  • value - can store character values of unlimited length ("text" field in the db)
/**
* Return the name of the field where the information is stored
* @return string
*/
public function datafield() : string {
	return 'intvalue';
}
instance_form_definition($mform)

Adds a field element to the instance course edit form. The form is passed into this function.

/**
* Add fields for editing a radio field.
*
* @param \MoodleQuickForm $mform
*/
public function instance_form_definition(\MoodleQuickForm $mform) {
	$field = $this->get_field();
	$config = $field->get('configdata');
	$elementname = $this->get_form_element_name();

	$radioarray=array();
	$radioarray[] = $mform->createElement('radio', $elementname, '', get_string('yes'), 1);
	$radioarray[] = $mform->createElement('radio', $elementname, '', get_string('no'), 0);
	$mform->addGroup($radioarray, 'cfgradioar', $config['cfgquestion'], array(' '), false);
	$mform->setDefault($elementname, $config['cfgdefault']);
	$mform->setType($elementname, PARAM_INT);
}

Please see the \core_customfield\data_controller class defined in /customfield/classes/data_controller.php for other functions.

See Also