General developer forum

Catching events triggered

 
Picture of Camille Tardy
Catching events triggered
 

Hi!


I'm trying to figure out if we can catch an event triggered by a plugin or the core.

If it's doable, how could we do it?

I've been browsing the forums and the developper docs but I came up empty.

If anyone can point me in the good direction it would be great.


Thanks for your help.


 
Average of ratings: -
Picture of Paul Holden
Re: Catching events triggered
Group Core developersGroup Particularly helpful MoodlersGroup Plugin developers

You need to write an observer method for the event you are interested in - see: https://docs.moodle.org/dev/Event_2#Event_observers

 
Average of ratings: -
Picture of Camille Tardy
Re: Catching events triggered
 

Thanks Paul,


I saw them on the event 2 page but their description is really vague and I couldn’t get what they were meant to do. 

Anyway thanks for the tip! 


Camille

 
Average of ratings: -
Davo
Re: Catching events triggered
Group Core developersGroup Particularly helpful MoodlersGroup Plugin developers

If you create a file called 'events.php' in the '/db' subfolder of your plugin and fill it in as described in the docs (with the name of the event and the name of the callback function) and bump your plugin version number (to get Moodle to recognise the changes you have made). Then, when the given event is triggered, the function you specified is called, with the event object as the parameter.

e.g. if you have an events.php file containing:

$observers = array(
    array(
        'eventname' => '\core\event\user_created',
        'callback' => '\local_myplugin\event_handler::user_created',
    ),
);

Then, in your plugin's '/classes' subfolder, you create a file 'event_handler.php' and fill it in with:

namespace local_myplugin;

class event_handler {
    public static function user_created(\core\event\user_created $event) {
        // Do something with this event, probably making use of $event->userid.
    }
}

Then your 'user_created' function will be called immediately after any new user account is created.

 
Average of ratings: Useful (1)
Picture of Iñaki Arenaza
Re: Catching events triggered
Group Core developersGroup Documentation writersGroup Particularly helpful MoodlersGroup Plugin developers

Hi Camille,

for a full (and very simple) example that expands on Davo's answer, you can have a look at my "Notify site administrators about new Email Signups" plugin (https://moodle.org/plugins/local_notifyemailsignup). You can browse the code at https://github.com/iarenaza/moodle-local-notifyemailsignup

Saludos. Iñaki.

 
Average of ratings: -
Picture of Camille Tardy
Re: Catching events triggered
 

Thanks Iñaki !

Yes


Camille

 
Average of ratings: -
Picture of Camille Tardy
Re: Catching events triggered
 

Thanks Davo for the detailed answer Yes

Camille

 
Average of ratings: -