2

The documentation provides a very comprehensive list of events provided by Craft but I would like to know if there is a way to get a list of those events at runtime.

Having such list would enable me to display a <select> field whereby a user could choose the event that should trigger an action.

Think of it as dynamic event registration!

3

Events don’t get pre-registered anywhere in Craft, so there’s no way to easily fetch a definitive list of all events that will ever get called, but with a little PHP we can get a pretty good idea of what they all are.

You’d start by getting a list of all the components on WebApp (what craft() returns) by calling its getComponents() method, loop through each of them, use reflection to get each of their methods, and find the ones that start with on. (By convention, all event methods should start with that, and non-event methods generally shouldn’t start with that, although it’s possible this will yield some false positives, so make sure you double-check the results.)

$events = [];
$components = craft()->getComponents(false);

foreach ($components as $id => $component)
{
    // Skip some non-existent components
    if ($id == 'fieldTypes' || $id == 'file')
    {
        continue;
    }

    // If the component hasn't been loaded yet, $component will just be its config array
    if (is_array($component))
    {
        $component = craft()->getComponent($id);
    }

    // Find the event methods
    $class = new \ReflectionClass($component);
    $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);

    foreach ($methods as $method)
    {
        if (strncasecmp($method->name, 'on', 2) === 0)
        {
            $events[] = $id.'.'.$method->name;
        }
    }
}

// Dump 'em out
Craft::dd($events);
| improve this answer | |
  • Exactly what I needed, thanks a bunch Brandon! – Selvin Ortiz Dec 4 '14 at 18:55
  • 1
    @SelvinOrtiz Just made a quick edit after testing locally - apparently we have a couple component definitions that shouldn't actually be there. I'll remove those for the next release, but for now you can just skip them with a quick conditional. – Brandon Kelly Dec 4 '14 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.