Custom fields API
Custom fields API overview
Custom fields API was added in Moodle 3.7. It allows to configure custom fields that can be added to various contexts. Each component (or plugin) that wants to use custom fields can define several areas. For example, 'core_course' component defines an area 'course' that allows to add custom fields to the courses, the same component can define another area 'coursecat' that will allow to add custom fields to the course categories. Inside each area the component/plugin can decide either to use or not to use itemid. For example, course custom fields are the same throughout the system and they don't use itemid (it is always 0). But there could be an activity module that would want to configure different custom fields for each individual instance of module, then this module would use the module instanceid as the itemid (example). This would allow to create modules similar to mod_data and mod_feedback where each instance has it's own set of fields.
New plugin type "customfield" was also added as part of the Custom fields API. Additional types of custom fields can be added to /customfield/field/ .
How to add custom fields
Component/plugin that uses custom fields must define a *handler class* for each area and a *configuration page*. Handler class must be called *<PLUGINNAME>/customfield/<AREA>_handler* and be placed in autoloaded location (<PLUGINDIR>/classes/customfield/<AREA>_handler.php . This class must extend *\core_customfield\handler* . Configuration page may be located anywhere. For course custom fields configuration the admin settings page is used /course/customfield.php. If the area uses itemid this page should take itemid as a parameter.
In the following examples we will use the course handler as an example. It has component=core_course, area=course, itemid=0
Configuration page contents will be:
$output = $PAGE->get_renderer('core_customfield'); $handler = HANDLERCLASS::create($itemid); $outputpage = new \core_customfield\output\management($handler); echo $output->render($outputpage);