Articles


How to create custom condition for the Rules event in Drupal 7

How to create custom condition for the Rules event in Drupal 7



Posted byUttam Kotekar,21st Jan 2016

In this post, lets discuss about how we can add custom condition for the rule event which we have created. It is very simple to create a custom condition for the event. Drupal itself provides a hook to create a custom rule condition info.

So let make a scenario to get better understanding of how we can use this condition. As in my previous post, we have discussed about creating an event "newsletter_register_email" and triggering mail for that event. So let add the rule condition for this event in such a way that trigger an email only if the user with specified role. So let create a custom condition for the rule.


/**
 * Implements hook_rules_condition_info().
 */
function example_rules_condition_info() {
  return array(
    'user_has_role_subscriber' => array(
      'group' => t('User'),
      'label' => t('Custom user specified role'),
      'parameter' => array(
        'user' => array(
          'type' => 'user',
          'label' => t('Validate registered users for subscriber role'),
        )
      ),
    ),
  );
}

/**
 * Callback function for custom condition info
 */
function user_has_role_subscriber($user) {
  // Subscriber role id is 3
  if (array_key_exists(3, $user->roles)) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

It is simpler to check condition for specified role via Rules config. Rules modules itself provides an condition info to check specified role. Please refer Add condition for user specified role via config. Above code is just an example to understand how we can add custom condition.

Lets now add the condition for the custom rule event "newsletter_register_email". Edit this rule, Under "condition" section you click on "Add condition". Once clicked will be redirected to "Add a new condition" page. Select the condition which we have created "Custom user specified role" under group "User". After continued on the data selector field, select "account" and save it. Thats it. Check the functionality now.

Categories