You are here

Custom Triggers in Drupal

Submitted by Anonymous (not verified) on October 7, 2011 - 8:34pm

Drupal allows you to define actions that will occur when specific system events occur. Those system events are called triggers. With some code you can add new triggers.

A default trigger is "New content submitted." That was too broad for my need, so I added a trigger "New content of type blogpost."

I found the instructions I needed at Scott Hadfield's blog post, "Creating Custom Triggers in Drupal".

The code below is a copy of his with one a simple change. Scott's cck content type is "script" and his module is also called "script." That is really confusing.

In my vesion, the custom code module is called customtrigger and my content type is called blogpost. Here is the code:

  1. <?php
  2.  
  3. /**
  4.  * Implementation of hook_hook_info().
  5.  */
  6. function customtrigger_hook_info() {
  7.   return array(
  8.     'customtrigger' => array(
  9.       'customtrigger' => array(
  10.         'insert' => array(
  11.           'runs when' => t('After a blogpost node is created'),
  12.         ),
  13.       ),
  14.     ),
  15.   );
  16. }
  17.  
  18. /**
  19.  * Implementation of hook_nodeapi().
  20.  */
  21. function customtrigger_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  22.   switch ($op) {
  23.     case 'insert':
  24.     	if ($node->type == 'blogpost') {
  25.       	module_invoke_all('myfunc', 'insert', $node);
  26.       }
  27.       break;
  28.   }
  29. }
  30.  
  31. /**
  32.  * Implementation of hook_myfunc().
  33.  */
  34. function customtrigger_myfunc($op, $node) {
  35.   $aids = _trigger_get_hook_aids('customtrigger', $op);
  36.   $context = array(
  37.     'hook' => 'blogpost',
  38.     'op' => $op,
  39.     'node' => $node,
  40.   );
  41.   actions_do(array_keys($aids), $node, $context);
  42. }

For more info read Scott's post. If you want to avoid adding custom code consider using the workflow module.