The Linux Page

Creating a Trigger in Drupal

I have been wondering, for a while, how the triggers where generated in Drupal. I know that one can catch a message by writing a hook function and you have hundreds of those available. However, how are the triggers working?!

The fact is that triggers require you to write a function. The Core Trigger module has a set of specialized functions for the Core modules and it is limited to that. In other words, you cannot expect new modules to simply define an array and get the triggers to work (I was really wondering how could that really work?!)

Okay, so I gave you the solution, but how does the code really look like?! You may want to have a look at the actions_do() function since that's the one function being called whenever a match is found. That function calls the corresponding action functions to apply that action. And the triggers function goes like this:

function my_module_do_actions($op, $p1, $p2, $p3...) {
  $aids = _trigger_get_hook_aids('my_module', $op);
  $context = array(
    'hook' => 'my_module',
    'op' => $op,
    'p1' => $p1,
    'p2' => $p2,
    ...
  );
  foreach ($aids as $aid => $action_info) {
    actions_do($aid, $p1, $context);
  }
}

Generally, you will have one or more parameters passed to the action function (i.e. similar to the parameters you pass to the module_invoke() function.) You then save those parameters in a context array. That context array will also include parameters as defined by your users (i.e. an email address.)

The $op parameter will correspond to a specific action as defined in your hook_hook_info() function.

You may want to check the modules/system/system.module for a good usage example.

Now, to implement actions, it is easier. You define a hook_action_info() function and define a set of actions in an array. This is easier, although the parameters you receive are not that clearly defined. You will get the context variable and that is expected to include most if not all the parameters available to you at the time the action is being executed. Again, there are good example in system.module, including the email one that let you create an advance action.

I will look a little further, but the same action can have many hooks. Each hook being a way to attach a trigger to that action. The concern to me is that you can only specify one callback and thus I'm not too sure how you can distinguish between the different parameters that will be passed to the callback. I'll post some more info once I have the answer.