Articles


How to create a custom rules event programmatically in Drupal 7

How to create a custom rules event programmatically in Drupal 7



Posted byUttam Kotekar,21st Jan 2016

Drupal 7 itself provides an interface to add a new rule event (admin/config/workflow/rules) via configuration. In most of the cases we create a rule via config but sometimes when we are dealing with complex functionality we might come across to create a custom rule event programmatically. It is very simple create a custom rule event programmatically and trigger it when required. Drupal itself provides a hook to create a custom rule event info.


/**
 * Implements hook_rules_event_info().
 */
function example_rules_event_info() {
  $items = array(
    'newsletter_register_email' => array(
      'label' => t('An event to trigger when an user is subscribed to newsletters.'),
      'group' => t('User'),
      'variables' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('updated user'),
        ),
      ),
    ),
  );
  return $items;
}

The above code creates an rule event "newsletter_register_email" and its been assigned to the group "User". You can create your own group depending upon your functionality. In case if you need to pass an argument to the customly created rule we have to make use of the type "variables". The above code states that $user account is passed as an argument to the custom rule event.

Now we have created custom rule and how we are going to trigger it. You can simply invoke the rule event by rules_invoke_event function.


rules_invoke_event('newsletter_register_email', $user);

Simply as that :-). If you need to trigger email for the custom rule event, you can refer Trigger mail for custom event rule.

Categories