Creating custom Drupal 7 rule events programmatically in code

Creating custom Drupal 7 rule events programmatically in code

With a new module comes the possibility that may require you to trigger an action based on new functionality. Using Rules, creating an event is actually very easy. And even easier is triggering that event in code so the action (and conditions) set in Rules can run.

I’m a fan of doing most logic in code, but I recently found Rules especially helpful when a client had many emails to be sent out based on a variety of node/user events. I easily created the events and they simply created the Rules and entered the mail content as they wanted to. MUCH easier than updating the email content through code (using drupal_mail of course).

/**
 * Implementation of hook_rules_event_info().
 */
function mymodule_rules_event_info() {
  return array(
    'mymodule_user_did_this' => array(
      'label' => t('A user did this'),
      'group' => t('My Module'),
      'variables' => array(
        'user' => array(
          'label' => t('The user that did something special'),
          'type' => 'user',
        ),
      ),
    ),
    'mymodule_node_did_that' => array(
      'label' => t('A node did that'),
      'group' => t('My Module'),
      'variables' => array(
        'node_type' => array(
          'label' => t('Article node did that'),
          'type' => 'node',
          'bundle' => 'article',
          'skip save' => TRUE,
        ),
      ),
    ),
  );
}

At this point, you’ll see these events in Rules and you can easily set actions for them.
To trigger these events, you would use:

rules_invoke_event('mymodule_user_did_this', $user);
// or
rules_invoke_event('mymodule_node_did_this', $node);

Simple as that 🙂

Comments are closed.