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

Old Events API

From MoodleDocs
Warning: This page is no longer in use. The information contained on the page should NOT be seen as relevant or reliable.
This legacy events API has been deprecated. See Events API for the new Events API.


The Events API is a core system in Moodle to allow communication between modules.

An event is when something "interesting" happens in Moodle that is worth alerting the system about.

Any Moodle modules can trigger new events (with attached data), and other modules can elect to handle those events with custom functions that operate on the given data.


Let's look at an example of how events are used to implement enrolment in Moodle 2.0. In the enrolment system, lib/enrollib.php will generate a 'user_enrolled' event upon completion of an enrolment of a user.

Triggering an event

When a user is enrolled, a 'user_enrolled' event is built and sent out by the enrol API. In this example let's pretend someone was just enrolled.

The enrol lib (could even be a module thats creating this event) needs to create an object with the data that this event needs. This may vary completely for different types of events, it's just a data object.

$ue = new stdClass();
$ue->enrolid      = $instance->id;
$ue->status       = is_null($status) ? ENROL_USER_ACTIVE : $status;
$ue->userid       = $userid;
$ue->timestart    = $timestart;
$ue->timeend      = $timeend;
$ue->modifierid   = $USER->id;
$ue->courseid  = $courseid;
$ue->enrol     = $name;

events_trigger('user_enrolled', $ue);

Then we post the object as an event and forget about it:

events_trigger('user_enrolled', $eventdata);

We have now broadcast an event that we think other parts of the system might need to know about.

Handling an event

Modules or core code can define an events.php in under its */db directory which defines events they want to be notified about, and describes which of their functions or class methods should be notified. For this case, there is this definition of a handler in mod/forum/db/events.php.

$handlers = array (
    'user_enrolled' => array (
        'handlerfile'      => '/mod/forum/lib.php',
        'handlerfunction'  => 'forum_user_enrolled',
        'schedule'         => 'instant',
        'internal'         => 1,

    'user_unenrolled' => array (
        'handlerfile'      => '/mod/forum/lib.php',
        'handlerfunction'  => 'forum_user_unenrolled',
        'schedule'         => 'instant',
        'internal'         => 1,

These events.php files are parsed during install / upgrade and stored in a simple database table.

Now, when a user_enrolled event happens, all the registered handlers functions for that event will be called something like this (but with more error handling):

          call_user_func($handlers['user_enrolled']['handlerfunction'], $eventdata);

Any code can hook into any events this way.

The handler function accepts one parameter (the event data object) and should return a boolean. Returning false indicates that there was an error and the event will be left in the event queue.

    function forum_user_unenrolled($eventdata) {
        // handle event 
        // ...
        return true;

note: a lib/db/events.php exists as legacy and no events should be added here. Core API is not supposed to define events for consumption. Only modules and core components (non-api) should define events for consumption/handling.

Database structure

There are 3 core tables for events. Note that if a handler is queued, and yet to be processed or processing failed, then all subsequent calls on that handler must be queued.


This table is for storing which components requests what type of event, and the location of the responsible handler functions.

These entries are created by parsing events.php files in all the modules, and can be rebuilt any time (during an upgrade, say).

Field Type Info
id int(10) auto increment identifier
eventname varchar(255) name of the event, e.g. 'message_send'
handlermodule varchar(255) e.g. moodle, mod/forum, block/rss_client
handlerfile varchar(255) path to the file of the function, eg /lib/messagelib.php
handlerfunction text serialized string or array describing function, suitable to be passed to call_user_func()
schedule varchar(255) 'cron' or 'instant'.
status int(10) number of failed attempts to process this handler


This table is for storing queued events. It stores only one copy of the eventdata here, and entries from this table are being references by the events_queue_handlers table.

Field Type Info
id int(10) auto increment identifier
eventdata longtext serialized version of the data object passed to the event handler.
stackdump text serialized debug_backtrace showing where the event was fired from
userid int(10) $USER->id when the event was fired
timecreated int(10) time stamp of the first time this was added


This is the list of queued handlers for processing. The event object is retrieved from the events_queue table. When no further reference is made to the events_queue table, the corresponding entry in the events_queue table should be deleted. Entry should get deleted (?) after a successful event processing by the specified handler. The status field keeps track of failures, after it gets to a certain number (eg 10?) it should trigger an "event failed" event (that could result in admin being emailed etc, or perhaps even the originating module taking care of it or rolling something back etc).

Field Type Info
id int(10) auto increment identifier
queuedeventid int(10) foreign key id corresponding to the id of the event_queues table
handlerid int(10) foreign key id corresponding to the id of the event_handlers table
status int(10) number of failed attempts to process this handler
errormessage text if an error happened last time we tried to process this event, record it here.
timemodified int(10) time stamp of the last attempt to run this from the queue

Standards for naming events

All event names should follow a consistent naming pattern, such as componentname_noun_verb (See Frankenstyle about the component name)

If the event is being fired after the action has taken place (as in most cases) then use the past tense for the verb (created / deleted / updated / sent).

If the event is the action, then use the present tense (create / delete / update / send).

Events which exist

When we add new events to core we should always add them here too.

Under each event, list the data sent as part of the event.


  • user_created
    • full new record from 'user' table (Event is trigger after profile fields are updated)
  • user_deleted
    • record from 'user' table before marked as deleted
  • user_updated
    • full new record from 'user' table (Event is trigger after profile fields are updated)
  • user_updated_password
    • contains userid and boolean for forgotten reset (Addded in 2.7)
  • user_enrolled
    • full user enrolment record (TBC)
  • user_logout
    • params TBC
  • user_loggedin
    • full record from user table
  • user_unenrol_modified
    • full user enrolment record (TBC)
  • user_unenrolled
    • full user enrolment record (TBC)


  • role_assigned
    • full new record from 'role_assignments' table
  • role_unassigned
    • record from 'role_assignments', course context only


  • course_created
    • full course record
  • course_updated
    • full course record
  • course_deleted
    • full course record
  • course_category_deleted
    • full category record
  • course_content_removed
    • full course record
  • course_restored (2.5)


  • groups_member_added
    • groupid, userid
  • groups_member_removed
    • groupid, userid
  • groups_group_created
    • id, courseid, name, description, timecreated, timemodified, picture
  • groups_group_updated
    • id, courseid, name, description, timecreated, timemodified, picture
  • groups_group_deleted
    • id, courseid, name, description, timecreated, timemodified, picture
  • groups_grouping_created
    • id, courseid, name, timecreated, timemodified
  • groups_grouping_updated
    • id, courseid, name, timecreated, timemodified
  • groups_grouping_deleted
    • id, courseid, name, timecreated, timemodified
  • groups_members_removed (user deleted from all groups in a course)
    • courseid, userid
  • groups_groupings_groups_removed (remove all groups from all groupings in a course)
    • courseid (as plain integer, not object)
  • groups_groups_deleted (delete all groups in a course)
    • courseid (as plain integer, not object)
  • groups_groupings_deleted (delete all groupings in a course)
    • courseid (as plain integer, not object)


  • cohort_added
    • full cohort record (TBC)
  • cohort_deleted
    • full cohort record (TBC)
  • cohort_member_added
    • cohort ID, user ID (TBC)
  • cohort_member_removed
    • cohort ID, user ID (TBC)
  • cohort_updated
    • full cohort record (TBC)


  • message_send
    • component = 'mod/forum': path in Moodle
    • name = 'posts': type of message from that module (as module defines it)
    • userfrom = $userfrom: a user object to send from
    • userto = $userto: a user object to send to
    • subject = 'subject line': a short text line
    • fullmessage = 'full plain text': raw text as entered by user
    • fullmessageformat = FORMAT_PLAIN|FORMAT_HTML|FORMAT_MOODLE|FORMAT_MARKDOWN: the format of this text
    • fullmessagehtml = 'long html text'; html rendered version (optional)
    • smallmessage = 'short text': useful for plugins like sms or twitter (optional)


  • portfolio_send
    • id : recordid in portfolio_tempdata table, used for itemid in file storage


  • assessable_file_uploaded
  • assessable_files_done
  • mod_created
  • mod_deleted
  • mod_updated
  • quiz_attempt_started
  • quiz_attempt_submitted - Note: these two quiz events changed in Moodle 2.1.

Events wishlist

List of events which it would be nice to have. Please add to this list if what you want is not shown here.

  • mform_print_form -- this for all types of form e.g. admin settings, user profile, module updating, + some sort of standard way of discriminating between them e.g. if ($form->name == 'user_profile') {}. This would be better triggered at the end of the form generation process so that new bits can be inserted at any point, or existing bits could be removed.
  • module_installed (= mod_created in v2?)
  • module_removed (= mod_deleted in v2?)
  • grade_update (= quiz_attempt_processed in v2?)
  • assignment_submitted
  • course - editing turned on or off
  • course completed
  • course module completion state changed (completed / not completed)
  • course was reset
  • Some will_be ... events that would allow another plugin to react before these things happen:
    • course_will_be_restored (with info about course being restored and the target category)
    • course_category_will_be_moved (with info about category being moved and target category)
    • course_will_be_moved (with course info and target category info)

Provide event trigger hooks for the modules, similar to what is done for the cron service which checks the LOCAL directory for a cron file. It is already possible to define an event trigger but the core/module code must be modified to actually make use of it.

See also