Monday, May 20, 2013

Programatically triggering Rules in Drupal 6

Sometimes a rule needs to be triggered and there is no existing event that can be used to trigger it.  The good news is that you can trigger events programatically without much trouble.

In this example we'll create a rule that sends an email to all users with a certain role.  We'll be writing this as a module for Drupal 6.

The first step is creating the event with hook_rules_event_info():

function modulename_rules_event_info() {
  return array(
    'modulename_event' => array(
      'label' => t('Event Name'),
      'module' => 'modulename',
      'arguments' => array(
        'user' => array('type' => 'user', 'label' => t('User.')),
        'node' => array('type' => 'node', 'label' => t('Node.'))
      ),
    ),
  );
}

Clear your Drupal cache to ensure that Drupal knows about your new event.

Now, navigate to the 'Rules' section on the Drupal admin area and create a new rule.  You should notice that your event is listed near the bottom of the 'events' select menu, under a heading of 'modulename'.

Continue to create the rule by defining conditions and actions to be evaluated when the event is triggered.

Now, to trigger the event programatically... enter this method in your module code at the point when the event should be fired:

rules_invoke_event('modulename_event', $user, $node);

An easy test is to send yourself an email with the rule, or use drupal_set_message() to output some text to the screen.

For more info see:  http://drupalcontrib.org/api/drupal/contributions%21rules%21rules%21rules.api.php/function/hook_rules_event_info/6

No comments:

Post a Comment