Automatic entry numbers in the Moodle Database activity
The Moodle Database activity has no automatic ID field. Our free datafield_autonumber numbers every entry, like REQ-0042, from the form, the app or a CSV import.
Short answer: the Moodle Database activity is often used as a simple register (equipment loans, room requests, incident reports, project ideas), but it has no field that numbers entries. People end up typing numbers by hand and getting duplicates. Our free plugin, datafield_autonumber, adds an Entry number field: every entry gets the next number when it is saved, like REQ-0042, and nobody can type or change it.
This is the sixteenth plugin in our series: one plugin for each Moodle plugin type, each one teaching DevLMS Studio, our AI plugin builder, how that type works. We checked the Moodle plugins directory first: it lists 9 Database field types, and none numbers entries.
How to use it
- In the Database activity, open Fields and create an Entry number field.
- Optionally set a Prefix (such as
REQ-) and the number of Digits to pad to (4 shows 42 as0042).
Entries already in the database are numbered in the order they were added. New entries get the next number however they arrive: the add entry page, the Moodle app, web services or a CSV import. Search finds REQ-0042, 0042 or 42, sorting puts 10 after 9, and exports include the number as shown. It supports Moodle 4.5 LTS to 5.3. The code is on GitHub.
Numbers of deleted entries are not reused, and two entries saved at the same moment never get the same number. A course backup and restore keeps both the numbers and the counter.
How a Database field works
From Moodle 5.3’s own Number field:
- A field type is one class that the Database activity calls to draw its settings, its input on the add entry form, its value in the templates, and its search and sort.
- Every way of adding an entry goes through one function, which announces the new entry with an event. The plugin numbers entries from that event, so it does not matter where the entry came from.
- The add entry page and the web service then create an empty value for every field. Left alone, that would give each entry two values for the number field, and lists sorted by it would show entries twice. The plugin removes the empty one when the request ends.
- The CSV import writes each column straight into the database unless the field handles imports itself. This field does, so a number in the file never overwrites the real one.
We found points 3 and 4 because the tests failed: one adds an entry through the web service, one copies exactly what the add entry page does, and one imports a CSV file. PHPUnit has 13 tests in all, including backup and restore, plus a browser test in which a student adds two entries and sees REQ-0001 and REQ-0002.
Need a plugin like this for your own Moodle?
Describe it in DevLMS Studio and watch it built and tested in a real Moodle, or ask our team for a fixed price.
Open DevLMS Studio