Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 80 additions & 55 deletions docs/apis/plugintypes/mod_data/fields.md
Original file line number Diff line number Diff line change
@@ -1,81 +1,106 @@
---
title: Database fields
tags:
- mod_data
- datafield
- plugintype
- subplugin
documentationDraft: true

### **Database Fields for Moodle 4.4.3**

---

The [Database activity](https://docs.moodle.org/en/Database_module) included with Moodle includes support for several predefined [field types](./fields.md), including text, date, and URL. It is also possible to create new field types. For example, you might like to create:
The **Database activity** in Moodle allows the creation of structured collections of data, with support for various predefined field types such as **text**, **date**, and **URL**. Additionally, developers can create new custom field types based on specific needs, enhancing flexibility and usability for institutions, modules, or disciplines.

#### **Custom Field Types Examples:**
- **Discipline-specific field types** – e.g., “Protein PDB code” allows users to enter a PDB code and display a 3D viewer of the protein structure or link to molecular databases.
- **Institution-specific field types** – e.g., “Library reference number” enables users to input a reference number that can be converted into a direct link to local library services.
- **Module-specific field types** – e.g., “Wiki page” field provides a dropdown list of wiki pages, allowing users to link database entries to specific wiki pages.

### **File Structure for Field Sub-Plugins**
Custom database field sub-plugins are stored in `/mod/data/field`. Each plugin resides in a separate subdirectory with mandatory files as well as any additional files developers wish to include.

---

- Discipline-specific field types - For example "Protein PDB code": users can enter the PDB code for a protein, and then the display 3D viewer for the protein structure, or link out to molecular databases.
- Institution-specific field types - For example "library reference number": Allow users to enter a reference number which can be automatically turned into a direct link for local library services.
- Module-specific field types - For example "wiki page": users see a drop-down list containing the names of pages in your wiki, and can choose which page this particular entry refers to.
#### **Mandatory Files for Field Plugins:**

- **`field.class.php`** (Required):
Defines the field type, behaviors, and properties. This class should be named `data_field_[pluginname]` and extend the `data_field_base` base class.

#### **Functions in the Field Class:**
The following functions can be overridden to customize behavior:

- **`display_add_field($recordid = 0)`**
Returns HTML for adding or editing a record.

- **`display_browse_field($recordid, $template)`**
Returns HTML to display a record in browse mode.

- **`update_content($recordid, $value, $name = '')`**
Saves the data entered by a user for a specific record.

- **`get_sort_sql($fieldname)`**
Specifies the SQL query for sorting field data.

- **`get_content_value($value)`**
Returns the value to display in the user interface, which may differ from the raw value stored in the database.

import { ComponentFileSummary } from '../../../_utils';
---

## File structure
### **Class Locations and Autoloading**
The field definitions for custom database fields are stored in `field.class.php` and should follow Moodle’s class structure. **Note**: Moodle 4.4.3 does not autoload these classes, so manual inclusion is still required. However, future versions of Moodle may introduce autoloading for field sub-plugins, so developers are encouraged to follow Moodle’s evolving [autoloading guidelines](https://moodledev.io/docs/guidelines/files/autoloading).

Database field sub-plugins are located in the `/mod/data/field` directory.
---

Each plugin is in a separate subdirectory and consists of a number of _mandatory files_ and any other files the developer is going to use.
### **Field Configuration Form**

<details>
<summary>View an example directory layout for the `datafield_number` subplugin.</summary>
- **File Path**: `/mod.html` (Required)
This file defines the form for adding or editing the field settings. The form is generated using Moodle's Form API and includes input fields relevant to the field type being created. Ensure the form is mobile-friendly and accessible, following Moodle’s UX standards.

```console
mod/data/field/number
├── classes
│   └── privacy
│   └── provider.php
├── field.class.php
├── lang
│   └── en
│   └── datafield_number.php
├── mod.html
└── version.php
#### **Form Example:**
```php
$mform->addElement('text', 'fieldname', get_string('fieldname', 'datafield_[pluginname]'), 'size="30"');
$mform->setType('fieldname', PARAM_TEXT);
$mform->addRule('fieldname', null, 'required', null, 'client');
```

</details>
**Important**: The field configuration process in Moodle 4.4.3 retains legacy elements, meaning it may not use the latest coding best practices. Developers are encouraged to update and modernize these forms where necessary, in line with Moodle’s [Form API guidelines](https://moodledev.io/docs/apis/core/dml/moodleform).

Some of the important files for the database field plugintype are described below. See the [common plugin files](../../commonfiles/index.mdx) documentation for details of other files which may be useful in your plugin.
---

### Field class
### **Security and Best Practices**

<ComponentFileSummary
filepath="/field.class.php"
required
summary="Definition of the field type"
/>
Moodle 4.4.3 includes several security updates, making it crucial for developers to ensure that custom field types follow Moodle's security standards. This includes proper validation and sanitization of user inputs. Use functions like `required_param()` and `optional_param()` to protect against SQL injection, XSS, and other common attacks.

The field, its behaviours, and its properties, are defined in a class named `data_field_[pluginname]` located in `field.class.php`. This class must extend the `data_field_base` base class.
Example:

:::danger Class locations
```php
$input = required_param('input', PARAM_ALPHANUM); // Ensures only alphanumeric values are accepted
```

The field definition is currently located in the `field.class.php` file and is not yet autoloaded by Moodle.
---

### **Testing and Compatibility**

:::
Custom field types should be tested across the platforms supported by Moodle 4.4.3. This includes:

The base class defines some simple behaviours which you can override in your plugin. The following functions are of particular interest:
- **PHP 8.1**
- **MariaDB 10.6.7**
- **MySQL 8.0**
- **PostgreSQL 13**
- **MSSQL 2017**
- **Oracle 19c**

- `display_add_field($recordid = 0)` - Return some HTML for use when a user is adding/editing a record
- `display_browse_field($recordid, $template)` - Return some HTML for displaying a record
- `update_content($recordid, $value, $name = '')` - Store the data entered by a user for a record
- `get_sort_sql($fieldname)` - Specify SQL for how this field should be sorted
- `get_content_value($value)` - Useful if the info stored in the database if different from the info that ends up being presented to the user
Testing for performance and stability across these environments ensures compatibility and reduces the risk of issues during deployment. Developers should also use Moodle’s [unit testing framework](https://moodledev.io/docs/apis/core/testing/phpunit) to automate testing for their plugins.

### Field configuration form
---

<ComponentFileSummary
filepath="/mod.html"
required
summary="Form definition for adding and editing the field configuration"
/>
### **Form API Updates**
Moodle continues to enhance its Form API for accessibility and improved UX. Make sure custom forms are responsive, accessible, and optimized for mobile devices. If any changes have been made to the Form API in Moodle 4.4.3, integrate them into your custom field plugins to take advantage of the improved user interface.

---

:::danger
### **Version Control and Deployment**
When developing custom fields, it’s recommended to use Moodle’s Git version control system for smooth deployment and updates. Developers should also ensure that their plugins are versioned and ready for the Moodle plugins directory.

The field definition is one of the older parts of Moodle and does not use best practice.
**Tags:** `mod_data`, `datafield`, `plugintype`, `subplugin`

:::
---

**Last updated on 2 October 2024.**

---
Loading