Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Drupal Rules How-to
Drupal Rules How-to

Drupal Rules How-to: Discover the power of the Rules framework to turn your Drupal 7 installation into an action-based, interactive application with this book and ebook.

Arrow left icon
Profile Icon Robert Varkonyi
Arrow right icon
$25.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (5 Ratings)
Paperback Nov 2012 74 pages 1st Edition
eBook
$14.39 $15.99
Paperback
$25.99
Arrow left icon
Profile Icon Robert Varkonyi
Arrow right icon
$25.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (5 Ratings)
Paperback Nov 2012 74 pages 1st Edition
eBook
$14.39 $15.99
Paperback
$25.99
eBook
$14.39 $15.99
Paperback
$25.99

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Drupal Rules How-to

Chapter 1. Drupal Rules How-to

Welcome to Drupal Rules. This book aims to present site builders and developers with tutorials that help them leverage the power of the Rules framework and turn their Drupal sites into event – action-based, interactive applications.

Rules can be used for building complex and flexible systems that respond to various system events, such as node creation, user registration, or viewing a comment. This book demonstrates the Rules framework in a learning curve style: from the basics, such as Reaction Rules, Events, Conditions, Actions, Components, and Scheduler, through advanced features such as using PHP in Conditions and Actions, combining Rules with other modules such as Views Bulk Operations and Flag to further extend the flexibility, to expertise API examples such as providing custom Events, Conditions, and Actions, creating new entity tokens and default rule configurations, and executing rule configurations programmatically.

Debugging Rules (Must know)

This recipe explains how to debug the rule configurations using the user interface.

How to do it...

  1. Go to Configuration | Workflow | Rules | Settings.
  2. Set Show debug information to Always.
  3. Save the form.
    How to do it...

How it works

Rules provides a very useful debugging system. This allows us to follow all the steps of a rule configuration as it's being executed. The following screenshot will show you if the Conditions evaluate and how long each step takes:

How it works

This is useful when our rule configuration doesn't work the way we want it to. It's always advised to use the debugger to see if the Conditions we used to evaluate the way we want them to. It's also useful that we're able to see how long each step takes. In this case, 16 ms is not a huge overhead when creating a node. However, if our rule configuration is set to fire Actions on each page load, it might lead to problems and it's advised to refactor that particular configuration.

There's more...

Despite there being user permissions related to the display of debugging information, it's advised that on production sites we don't display debug information on the UI. Instead, we make Rules write the logs into the log file by setting the value Log debug information to the system log on the Settings page, as shown in the following screenshot:

There's more...

The following recipes describe some more advanced features of the Rules framework, including the usage of PHP in Conditions and Actions and explains how to use Rules together with other modules, such as Flag, Views Bulk Operations, and Rules Bonus Pack.

Using PHP in Conditions and Actions (Should know)

This section explains how to use PHP input in Conditions and Actions.

In this simple example we'll display a message on the front page every Monday. To do that, we'll use a PHP input in our Condition to evaluate to TRUE if we're currently on the front page of our site, and if it's Monday today.

Getting ready

Enable the PHP Filter module on Drupal's module list page and assign relevant permissions if necessary. Take extra care as to whom you assign these permissions to, as the PHP input may cause security concerns so you probably don't want everyone on your website to be able to use it.

How to do it...

  1. Add a new rule configuration and set the Event to System | Drupal is initializing.
  2. Add a new Condition, Data | Data comparison and set it to site:current-date.
    How to do it...
  3. In the DATA VALUE field set, click on Switch to data selection and enter site:current-date.
    How to do it...
  4. In the PHP EVALUATION field, enter the Code value, as shown in the following screenshot, and save the Condition:
    How to do it...
  5. Add a new Condition and set the handler to PHP | Execute custom PHP code and enter this code in the text area:
    How to do it...
  6. Add a new Action, System | Show a message on the site and enter the following Value, as shown in the screenshot:
    How to do it...

How it works...

In the first Condition, we compare the current date value to figure out what day it is today. In the PHP Evaluation field, we always receive the value of the selected field in the $value variable, which in this case is a timestamp of the current date. We're using this value in Drupal's format_date() function to return TRUE if it's Monday today.

In the second Condition, we're returning TRUE if the current page we're visiting is the front page of our website.

There's more...

PHP can be put to use in many other ways too. Some are described as follows:

Using PHP in Actions

We can also use PHP in Actions to execute functions, update database entries, and perform other tasks as required. To do that we can add an Action, Execute custom PHP code, and enter the PHP code we want to execute.

Best practice

Using a PHP input in Rules is a very effective way to create custom Conditions and Actions if we don't want to programmatically create new ones in our custom module (more on that in the Providing new Events, Conditions, and Actions (Become an expert) recipe in this book). However, there are a number of things we want to keep in mind:

  • Permissions

    It is highly advised that we don't let regular users use the PHP input filter, as it is a high security risk.

  • Never use delimiters

    We should never use the <?php ?> delimiters in our custom code. Rules takes care of that for us. If we use the delimiters in our Condition or Action, it won't work.

  • Always test on a development site

    Of course, it is advised that all Rules configurations are tested on a development site before using them on production sites. This is particularly valid for configurations that include the PHP code in Conditions or Actions. We always want to make sure we enter code without typos, execute the right database commands, or update the right user information.

    It is also advised that Debugging is turned on on our development site, that way we can save a lot of time testing our configuration.

Using condition groups (Should know)

This recipe describes the usage of condition groups and the ability to combine Conditions.

We'll create a rule that sends an e-mail to the administrators if either a new article or any content type gets posted on the site that has an image field (field_image).

How to do it...

  1. Create a new rule configuration and set the Event to Node | After saving new content.
  2. Add a new Condition, Entities | Entity is new.
  3. Add an OR Group.
    How to do it...
  4. Add a new Condition to the group by clicking on Add condition in the group's row, as shown in the following screenshot:
    How to do it...
  5. Add the Condition, Node | Content is of type and set the content type to Article.
  6. Add another Condition to the OR group, use Entities | Entity has field and set the field to field_image.
  7. Add an Action to the rule configuration, use System | Send email to all users of a role, select the administrators role and fill out the SUBJECT and MESSAGE fields.

How it works...

To create complex Conditions, in Rules we can use condition groups. This way we can create a chain of Conditions using AND or OR groups. AND groups require all Conditions within the group to evaluate to TRUE, while OR groups require only one Condition to evaluate to TRUE.

There's more...

The following section describes combining of conditional groups:

Combining condition groups

We can also combine condition groups, that means we can create condition groups within condition groups. Again, it is advised that Debugging is turned on when creating nested condition groups as it can save a lot of time figuring out why a configuration doesn't work as expected.

Subscribe to comments on a node using Rules and Flag (Should know)

This recipe explains how to use Rules and Flag to send out e-mail notifications to users when someone comments on a node users are subscribed to.

Getting ready

Install and enable the Flag module.

How to do it...

  1. Create a new flag configuration at Structure | Flags.
    How to do it...
  2. Enter a name and set the type to Nodes.
    How to do it...
  3. Enter Subscribe as the label for the new Flag and set and Flaggable content to Article, as shown in the following screenshot, and save the Flag configuration:
    How to do it...
  4. Create a new rule configuration at Configuration | Workflow | Rules, set the Event to Comment | After saving a new comment.
  5. Add an Action, Flag | Fetch users who have flagged a node, as shown in the following screenshot:
    How to do it...
  6. Set the Flag to the new flag configuration we created.
    How to do it...
  7. We want to act on the node the comment belongs to, so we'll use the comment's node in the Data selector field and save the Action, as shown in the following screenshot:
    How to do it...
  8. Add a new loop in the Actions section and select users in the Data selector section, as shown in the following screenshot:
    How to do it...
  9. Optionally, set the variable name to something that's more descriptive, as shown in the following screenshot, and save the loop.
    How to do it...
  10. Add a new Action within the loop System | Send mail and configure the various fields using REPLACEMENT PATTERNS.
    How to do it...
  11. Fill in the TO text area. Note, that we make use of a-user:mail token, which became available to Rules in the previous step, when defining the loop and setting the labels of the current list item.
  12. Enter the subject. Again, the a-user:name token is used, which will be replaced with the name of the user in the loop.
    How to do it...
  13. Enter the message. Here we make use of other available tokens. This is shown in the following screenshot:
    How to do it...

How it works...

In this recipe, we're creating a new flag configuration for article nodes and using that in our rule configuration to get the list of users that are subscribed to a node that's being commented on (using the Flag we created), and send them a notification e-mail. Flag provides a list data type (Fetch users who have flagged a node) that Rules can use to create a loop of all users who flagged a node, and act on each individual object.

There's more...

Flag provides various Events, Conditions, and Actions that we can use in our rule configurations.

Events

A node can be flagged or unflagged: This acts on Events that involve flagging or unflagging a node, user, or comment.

Conditions

The following are the Conditions provided by Flag:

Node/Comment/User is flagged: This checks if the entity is already flagged.

Node/Comment/User has flagging count: This checks the number of flags an entity has.

Actions

The Action for fetch users who have flagged a comment/node/user creates a list of users who have flagged an entity. The data will be provided to Rules as a list type, so it can execute a looped action on each individual object.

Flag a comment/node/user: This programmatically flags an entity.

Trim a flag: This sets the maximum number of flags an entity can have.

Unflag a comment/node/user: This programmatically unflags an entity.

Adding a taxonomy term to a node using Views Bulk Operations and Rules (Should know)

This recipe describes how to add a specific taxonomy term to a list of nodes using Views Bulk Operations (VBO) and Rules.

Getting ready

Install and enable Views, Views UI, and Views Bulk Operations. Go to Structure | Views and create a new table view that lists all nodes posted on the site, and add a Bulk operations: Content field to it.

How to do it...

  1. Create a new rule component, select the Rule plugin and require an Entity | Node parameter. Name the new component Add taxonomy term to node.
  2. Add a Condition, Entities | Entity has field, use node as the entity, and set the field to field_tags.
    How to do it...
  3. Add a new Action, Data | Add an item to a list and set the value to node:field-tags.
    How to do it...
  4. In the Item to add fieldset, click on the Switch to the direct input mode button and enter the ID of the taxonomy term to add, as shown in the following screenshot:
    How to do it...
  5. Go back to the view and click on the Bulk Operations: Content field.
  6. In the popup window, select the rule component we created in the SELECTED OPERATIONS fieldset, as shown in the following screenshot:
    How to do it...

How it works...

Views Bulk Operations can use Rules components to execute Actions on a list of entities and objects. We can create the Rules components with parameters and VBO will make these components available as operations in our Bulk Operations field configuration, if the field type matches the component's parameter type. For example, when creating a component that requires a Node parameter, we need to add the same type of VBO field (Content: Bulk Operations) to the view, because this is how VBO determines what kind of parameter is being passed to Rules.

There's more...

If we want this feature to be a bit more flexible and choose a taxonomy term, we want to add to the nodes instead of always adding a preconfigured term ID, we can do the following:

  1. Add a new Entity | Taxonomy term parameter to our component, set the machine name to the term.
  2. Edit our Action, Add an item to a list, in the Item to add fieldset, click on Switch to data selection, and enter term. This is given in the following screenshot:
    There's more...

    Now when executing the operation, VBO will display a configuration screen where we can enter the ID of the taxonomy term we want to add to the node.

Loading a list of objects into Rules using VBO (Should know)

This recipe explains how to load the result of a VBO view into Rules.

We will create a view that lists all nodes that are:

  • Created by user 1 (admin)
  • Promoted to the front page
  • More than two weeks old

We will then demote these nodes from the front page using Rules.

Getting ready

Install and enable Views, Views UI, and Views Bulk Operations.

How to do it...

  1. Go to Structure | Views and create a new view that lists all the nodes that are created by user 1, are promoted to front page, and are more than two weeks old, and add a VBO field to it. Call this new view Old admin content.
    How to do it...
  2. Go to Configuration | Workflow | Rules | Components and add a new Action set component. No parameters are needed; we will get the objects from the view.
  3. Add a new Action, Views Bulk Operations | Load a list of entity objects from a VBO View and select the view we created in the first step, as shown in the following screenshot:
    How to do it...
  4. Optionally, enter a descriptive label for the variables and save the Action.
    How to do it...
  5. Add a new loop in the Actions section and select the VBO view result as the list data, shown as follows:
    How to do it...
  6. Optionally, enter a descriptive label for the variable to be used in the loop.
    How to do it...
  7. Add a new Action within the loop Node | Remove content from front page, as shown in the following screenshot:
    How to do it...
  8. Select the current node to be removed from the front page.
    How to do it...

How it works...

VBO views can be used to create a list of objects for Rules to execute an action on. This is a useful feature for developers and site builders who make extensive use of views on their sites. The advantage of using this feature is that we can create complex views with relationships and contextual filters (Rules provides an interface to pass arguments to views) and perform actions on the results.

In this example, we will create a new view that lists nodes that are created by user 1 (admin), are promoted to the front page, and are posted two weeks ago or earlier. Then, by adding a VBO field to the view, we make the results of the view available for Rules to use. Because the data type provided to Rules is a list, we can create a loop in our action and perform operations on each individual item.

Rules Bonus Pack (Should know)

This recipe describes some extra Rules functionality added by the Rules Bonus Pack module. This module is a set of extensions and integrations with other modules to extend Rules to provide additional Events, Conditions, and Actions and also integrate with other modules, such as CTools.

In this example, we will act on the node view by modifying the page title to include the node's associated taxonomy terms.

Getting ready

Download Rules Bonus Pack and enable Rules Bonus: Miscellaneous.

How to do it...

  1. Create a new rule configuration, set the Event to Node | Content is viewed.
    How to do it...
  2. Add a Condition, Entities | Entity has field, use node as the entity and select field_tags as the field to check for.
  3. Add an Action, Rules Bonus: Miscellaneous | Set page title.
    How to do it...
  4. Use REPLACEMENT PATTERNS to modify the page title.
    How to do it...

How it works...

In this example we've used a custom action provided by the Rules Bonus Pack module. We tell Rules to act on a node view by modifying the node's title, if it has any tags associated with it. For safety, we could also add a Condition, Data | Data value is empty, set it to node:field-tags, and check Negate to make sure we only do that if the node actually has terms.

There's more...

Rules Bonus Pack provides a number of essential extensions to the Rules framework. The following is a list of the main features:

  • CTools / Page manager integration: Rules Bonus Pack provides a bridge between the Page manager and Rules. It can provide an Event for viewing each custom page variant, which is useful when using Panels and Rules together.

    Rules Bonus Pack also provides integration with the Page manager's Access control feature. We can create condition components that can be used by the Page manager to determine whether a user can access the custom page.

  • Blocks and Theme related Actions: Rules Bonus Pack provides various Block and Theme related Actions. By enabling Rules Bonus: Block and Rules Bonus: Theme modules, we get access to various Actions, such as, placing a block in a region based on a condition or adding a custom CSS class to the body.

These recipes target developers who wish to extend Rules with their own custom Events, Conditions, and Actions. We'll also learn how to provide new entity tokens for Rules to use, how to execute rule configurations in code, and how to provide default rule configurations in our custom module.

The code snippets in these recipes are for demonstration purposes only. They are intended only to explain a specific hook or functionality and do not always provide a generic solution to a problem.

Providing new Events, Conditions, and Actions (Become an expert)

This recipe explains how to create our custom Events, Conditions, and Actions.

In this example, we'll act on a view that's being rendered on the site. We'll create a new condition, where we set the view that's being rendered, and in our action, we'll update a custom database table with the number of times the view has been rendered.

Getting ready

Enable the Views and Views UI modules, and create a view of the latest content on the site. In this example, we'll use the latest content as the view name, and create a block displaying the latest content by the admin that lists all new content posted by user 1.

We also need to create a new database table where we'll store the information; we'll call it custom_view_render. We use hook_schema() in our .install file so our custom table will be available in all supported database engines automatically.

How to do it...

  1. Create a new custom module with the following structure:
    {modules_folder}/custom/
     custom.info
     custom.module
     custom.rules.inc
     custom.install
  2. Define the module's information in the custom.info file:
    name = Custom
    description = Provides an integration with the Rules framework to store the number of times a view was rendered
    core = 7.x
    package = Rules Custom
    dependencies[] = rules
    dependencies[] = rules_admin
    dependencies[] = views
    dependencies[] = views_ui
  3. Define our custom database table in the custom.install file:
    /**
     * Implements hook_schema()
     */
    function custom_schema() {
      $schema['custom_views_render'] = array (		
        'description' => 'The base table for custom views render.',
        'fields' => array(
          'view' => array(
            'description' => 'The name and display ID of the view.',
            'type' => 'varchar',        
            'length' => '32',
            'not null' => TRUE,
            'default' => '',
          ),
          'rendered' => array(
            'description' => 'The number of times the view was rendered.',
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,       
          ),      
        ),       
        'primary key' => array('view'),
      );
      return $schema;
    }
  4. Define our new custom Event in custom.rules.inc:
    /**
    * Implements hook_rules_event_info()
    * Define our new custom event for Rules
    */
    function custom_rules_event_info() {
      return array(
        'custom_views_render' => array (
          'label' => 'A view is rendered',
          'group' => 'Rules Custom',
          'variables' => array(
            'view' => array(
              'type' => 'custom_view_datatype',
              'label' => t('View being rendered')
            )
          )
        )
      );
    }
  5. Because views are not regular data types natively available to Rules; we provided the custom_view_datatype type as the variable type. We also need to define this new data type in our hook_rules_data_info() function:
    /**
     * Implements hook_rules_data_info().
     * This hook should be used to define new data types to Rules.
     *
     * In this case, we simply pass on the view object to Rules
     */
    function custom_rules_data_info() {
      return array(
        'custom_view_datatype' => array(
          'label' => t('view')			
        ),
      );
    }
  6. We want Rules to invoke our event when a view is being rendered, so we'll use hook_views_pre_render() in custom.rules.inc and use rules_invoke_event_by_args() function to notify Rules that the event needs to be invoked:
    /**
     * Implements hook_views_pre_render()
     * Invoke our custom event when a view is being rendered
     */
    function custom_views_pre_render(&$view) {
      rules_invoke_event_by_args('custom_views_render', array($view));
    }
  7. Define our new Condition, that will compare a rendered view's name and display ID with a specified view:
    /**
    * Implements hook_rules_condition_info()
    */
    function custom_rules_condition_info() {
      return array(
        'custom_views_condition' => array(
          'label' => t('View being rendered'),
          'parameter' => array(
            'view' => array(
              'type' => 'text',
              'label' => t('View and display'),
              'options list' => 'custom_views_list',
              'description' => t('Select the view and display ID'),
              'restriction' => 'input',
            ),
          ),
          'group' => t('Rules Custom')
          )
      );
    }
  8. In the options list attribute, we define a custom function custom_views_list that returns an array of the available views on our site:
    /**
     * Helper function that returns all available views on our site
     */
    function custom_views_list() {
      $views = array();
      foreach (views_get_enabled_views() as $view_name => $view) {
        foreach ($view->display as $display_name => $display) {
          $views[$view_name . '-' . $display_name] =
          check_plain($view->human_name) . ' - ' . check_plain($display->display_title);
        }
      }
      return $views;
    }
  9. The array key custom_views_condition, defined in our custom_rules_condition_info() function, will be used to execute the actual comparison that will return a Boolean value, so we'll add a function with the same name:
    /**
     * Callback function for our custom condition
     * The function name must match the array key defined in hook_rules_condition_info()
     */
    function custom_views_condition($view = array()) {
      $current_view = views_get_current_view();
      $parts = explode('-', $view);
      if (($parts[0] == $current_view->name) && ($parts[1] == $current_view->current_display)) {
        return TRUE;
      }
      return FALSE;
    }
  10. Let's create our custom Action for Rules:
    function custom_rules_action_info() {
      return array(
        'custom_update_table' => array(
          'label' => t('Update "custom_views_render" table'),
          'parameter' => array(
            'view' => array(
              'type' => 'custom_view_datatype',
              'label' => t('Rendered View'),
            ),
          ),
          'group' => t('Rules Custom')
          ),
      );
    }
  11. We also need to add a function that actually gets called by Rules when the action fires. The name of this function must match the value of the "base" attribute defined in hook_rules_action_info():
    /**
     * The database function that gets called by the Rules Action
     * The function name must match the value in the 'base' attribute
     * defined in hook_rules_action_info()
     */
    function custom_update_table($view) {
        if (!is_object($view)) {
          return FALSE;
        }
        $result = db_select('custom_views_render', 'c')
          ->fields('c')
          ->condition('view', $view->name .'_'. $view->current_display, '=')
          ->execute()
          ->fetchAssoc();
    
        if ($result) {
          $update = db_update('custom_views_render')
          ->expression('rendered', 'rendered + :one', array(':one' => 1))
          ->condition('view', $view->name .'_'. $view->current_display, '=')
          ->execute();
        }
        else {
          $insert = db_insert('custom_views_render')
          ->fields(array(
            'view' => $view->name .'_'. $view->current_display,
            'rendered' => 1
          ))
          ->execute();
        }
    }

    The last step is to create a new rule configuration, set the Event to Rules Custom | A view is rendered, add a Condition Rules Custom | View being rendered and set it to our latest content view, and add an Action Update "custom_views_render" table:

  12. Set the Event.
    How to do it...
  13. Add the Condition.
    How to do it...
  14. Set the view and display ID in the Condition, as shown in the following screenshot:
    How to do it...
  15. Add our custom Action:
    How to do it...
  16. Set the rendered view's Data selector value to the view object provided by our event:
    How to do it...

How it works...

In this example, we're creating a custom workflow by providing a new Event, Condition, and Action. In this virtual example, we want to track how many times a given view has been rendered. First we create a new database table to store the data in. Then we define our custom Event (A view is rendered) and our Condition (View being rendered) where we can choose the view and display that's being rendered. In the last step, we define our Action (Update "custom_views_render" table) which takes care of the database operations. Then we go ahead and create the rule configuration using our new Event, Condition, and Action.

It is the best practice to add all Rules hooks to a custom *.rules.inc file. Rules will automatically detect this file and fire the hooks.

There's more...

The following sections provide more information on creating Events, Conditions and Actions, and clearing caches.

Events

To create new Events for Rules, we need to implement hook_rules_event_info(). In this hook we need to return an array of Events, with the keys becoming the machine readable names of the Events. We can define the label, group, and variables this event will use. We can then fire this event by using rules_invoke_event() or rules_invoke_event_by_args() in another function or hook.

Conditions

We can define new Conditions by implementing hook_rules_condition_info(). Again, we need to return an array of Conditions with the array keys becoming the machine readable names of the Conditions, and by default, Rules will look for a function with the same name which will be fired when the Condition is invoked. Therefore, we need to create a function using the same machine readable name.

We must also define the parameters used by the condition. These parameters will be used in the custom function that returns either TRUE or FALSE.

Actions

When defining new Actions, we need to implement hook_rules_action_info(). Actions have a similar structure to Conditions, the definition consists of an array with information about the Action and a callback function that gets fired. The main difference is that an Action may execute an operation or return additional data for Rules.

Clearing the caches

Rules and the Entity API uses a fair amount of caching in order to increase performance. Therefore these caches need to be cleared every time a new Event, Condition, or Action is defined.

Providing new entity tokens (Become an expert)

This recipe demonstrates how to provide new entity tokens for Rules. Entity tokens provides a way to use placeholders in Rules (and other modules) and dynamically replace them with chunks of data.

In this example, we'll provide the current number of registered users on our site as a globally available token for Rules.

How to do it...

  1. Implement hook_entity_property_info() to provide our new entity token:
    /**
     * Implements hook_entity_property_info()
     * We extend the natively available 'site' properties
     */
    function custom_entity_property_info() {
        $info = array();
        $properties = &$info['site']['properties'];	
        $properties['registered_users'] = array(
          'label' => t("Number of registered users"),
          'type' => 'integer',
          'description' => t("Returns the current number of registered users on the site."),
          'getter callback' => 'custom_number_of_users'
        );
        return $info;
    }
  2. We've defined custom_number_of_users as the callback function in the getter callback property, so we'll create this function:
    /**
     * Callback function that returns the current number of registered users
     */
    function custom_number_of_users() {
      $result = db_query("SELECT count(*) FROM {users} WHERE uid > 1")->fetchField();
      return $result;
    }
  3. The newly created entity token will be available to use in Conditions and Actions in REPLACEMENT PATTERNS:
    How to do it...

How it works...

By implementing hook_entity_property_info(), we're providing the Entity API information about our new entity token. The function that returns data needs to be defined in the getter callback property. Implementing this hook makes it possible to use new tokens in the rule configurations, or any other configuration that uses Entity API.

Executing Rules programmatically (Become an expert)

This recipe explains how to execute Actions, Rules, or Rule sets programmatically.

In this example, we'll create a simple component that sends an e-mail to the site administrators and execute this component programmatically.

How to do it...

  1. Add a new action set component, call it Send message to all admins:
    How to do it...
  2. Add a new Action, System | Send message to all users of a role.
  3. Select administrators in the ROLES select box:
    How to do it...
  4. Enter some text to the SUBJECT text field:
    How to do it...
  5. Enter a message and save the component:
    How to do it...
  6. Now that we've created our component, we can execute it in our custom module using rules_invoke_component():
    <?php
    rules_invoke_component('send_message_to_all_admins');
    ?>

How it works...

Components can be executed programmatically using the rules_invoke_component() function. The first parameter of the function will receive the machine readable name of the component, followed by any additional parameters that the component requires. This way we can execute complex Actions, Rules, Rule sets, Conditions, or additional plugins defined by other modules.

There's more...

The following section describes the execution of standalone plugins programmatically.

Executing standalone plugins

It's also possible to programmatically execute plugins without combining them into a component. We can, for example, execute a Condition in the following way:

<?php
$condition = rules_condition('user_has_role', array('role' => array('editor')));
$condition->execute($user);
?>

Providing new variables for Actions (Become an expert)

This example explains how to modify existing or provide new variables and data for Rules in Actions.

We'll extend our previously defined action with a new one that provides additional data to Rules after the action is executed. In this case, the data provided to Rules is the number of currently registered users on the site.

Getting ready

This recipe is based on the recipe Providing new Events, Conditions, and Actions (Become an expert) in this book.

How to do it...

  1. Add a new associative array to our hook_rules_action_info() function and instead of "parameters" we'll use the "provides" property:
    'custom_registered_users' => array(
    'label' => t('Get number of registered users'),
        'provides' => array(
          'number_of_users' => array(
            'type' => 'integer',
            'label' => t('Number of users')
          ),
        ),
        'group' => t('Rules Custom')
    )
  2. Create the callback function that returns an array in the format Rules expects it:
    /**
    * Callback function that returns the current number
    * of registered users and returns it to Rules in an
    * array
    */
      function custom_registered_users() {
        $result = db_query("SELECT count(*) FROM {users} WHERE uid > 1")->fetchField();	
        // Return an array for Rules with the array key
        // being the machine readable name defined in the
        // 'provides' property
        return array(
           'number_of_users' => $result
        );
      }
  3. After clearing caches, the newly created action will be available in the list of Actions:
    How to do it...
  4. Optionally we can modify the variable's label and suggested machine readable name in the next configuration screen.
    How to do it...

Tip

When adding additional Actions our new variable becomes available to Rules. For the purpose of this example, we'll add the Action, System | Show a message on the site and display the results in the MESSAGE field. Note that the created variable doesn't become available as a token, so we need to Switch to data selection and select the variable from the drop-down list.

How to do it...

How it works...

Actions can provide new variables to Rules by making use of the provides property in hook_rules_action_info(). The data structure is almost identical to the way we declare parameters, the only difference is that user input is not allowed. By providing new variables to Rules, we can execute complex functions in an action and then work with their return data while still in Rules.

Providing default rule configurations (Become an expert)

This recipe explains how to provide default rule configurations in code. The advantage of that is that we can keep our configurations in code and use version control, such as, SVN or Git.

How to do it...

  1. In our custom module's folder, we add a new file called custom.rules_defaults.inc and declare the rule configuration by implementing hook_default_rules_configuration(). The contents of the file are as follows:
    /**
    * Implements hook_default_rules_configuration()
    */
    function custom_default_rules_configuration() {
      $rule = rules_reaction_rule();
      $rule->label = 'Default Rule';
      $rule->active = TRUE;
      $rule->event('node_insert')
      ->condition('data_is', array('data:select' => 'node:type',       'value' => 'article'))
      ->condition(rules_condition('data_is', array('data:select' =>       'node:author:uid', 'value' => 1))->negate())
      ->action('drupal_message', array('message' => 'Hey [node:author], thanks for creating a new article!'));
    
      $configs['custom_default_rule'] = $rule;
      return $configs;
    }
  2. After clearing the caches, our newly created default rule will become available in the list of configurations, as shown in the following screenshot:
    How to do it...

How it works...

Using hook_default_rules_configuration(), we can define our rule configuration in code using Rules' methods for Events, Conditions, and Actions. Rules will look for a file *.rules_defatuls.inc in our module's folder, and automatically add our default rule to the available configurations after clearing the caches.

There's more...

Rules is compatible with the Features module, which provides a centralized API for exporting and importing configuration from the database. This is also an effective way to manage configuration in code and version control systems.

Altering default rule configurations

It is also possible to modify a default rule configuration in code. For that we could use hook_default_rules_configuration_alter() in our *.rules_defaults.inc file.

  /**
   * Implements hook_default_rules_configuration_alter()
   */
  function custom_default_rules_configuration_alter(&$configs) {
    $configs['custom_default_rule']->condition('data_is', array('data:select' => 'node:is_new', 'value' => TRUE));
  }

Making changes to the configuration on the UI

Rules tracks the state of a Rule configuration that has been added programmatically. What that means is that it can determine whether an imported configuration is in its default state (not modified compared to the code) or overridden (modified using the UI, but not in code). When a configuration is modified, Rules allows to revert it back to its original state.

Making changes to the configuration on the UI

By clicking on that, we're telling Rules that it should re-read the configuration that we've defined in code and revert it to its original state.

Loading a list of objects into Rules using VBO (Should know)


This recipe explains how to load the result of a VBO view into Rules.

We will create a view that lists all nodes that are:

  • Created by user 1 (admin)

  • Promoted to the front page

  • More than two weeks old

We will then demote these nodes from the front page using Rules.

Getting ready

Install and enable Views, Views UI, and Views Bulk Operations.

How to do it...

  1. Go to Structure | Views and create a new view that lists all the nodes that are created by user 1, are promoted to front page, and are more than two weeks old, and add a VBO field to it. Call this new view Old admin content.

  2. Go to Configuration | Workflow | Rules | Components and add a new Action set component. No parameters are needed; we will get the objects from the view.

  3. Add a new Action, Views Bulk Operations | Load a list of entity objects from a VBO View and select the view we created in the first step, as shown in the following screenshot:

  4. Optionally, enter a descriptive label for the variables and save the Action.

  5. Add a new loop in the Actions section and select the VBO view result as the list data, shown as follows:

  6. Optionally, enter a descriptive label for the variable to be used in the loop.

  7. Add a new Action within the loop Node | Remove content from front page, as shown in the following screenshot:

  8. Select the current node to be removed from the front page.

How it works...

VBO views can be used to create a list of objects for Rules to execute an action on. This is a useful feature for developers and site builders who make extensive use of views on their sites. The advantage of using this feature is that we can create complex views with relationships and contextual filters (Rules provides an interface to pass arguments to views) and perform actions on the results.

In this example, we will create a new view that lists nodes that are created by user 1 (admin), are promoted to the front page, and are posted two weeks ago or earlier. Then, by adding a VBO field to the view, we make the results of the view available for Rules to use. Because the data type provided to Rules is a list, we can create a loop in our action and perform operations on each individual item.

Rules Bonus Pack (Should know)


This recipe describes some extra Rules functionality added by the Rules Bonus Pack module. This module is a set of extensions and integrations with other modules to extend Rules to provide additional Events, Conditions, and Actions and also integrate with other modules, such as CTools.

In this example, we will act on the node view by modifying the page title to include the node's associated taxonomy terms.

Getting ready

Download Rules Bonus Pack and enable Rules Bonus: Miscellaneous.

How to do it...

  1. Create a new rule configuration, set the Event to Node | Content is viewed.

  2. Add a Condition, Entities | Entity has field, use node as the entity and select field_tags as the field to check for.

  3. Add an Action, Rules Bonus: Miscellaneous | Set page title.

  4. Use REPLACEMENT PATTERNS to modify the page title.

How it works...

In this example we've used a custom action provided by the Rules Bonus Pack module. We tell Rules to act on a node view by modifying the node's title, if it has any tags associated with it. For safety, we could also add a Condition, Data | Data value is empty, set it to node:field-tags, and check Negate to make sure we only do that if the node actually has terms.

There's more...

Rules Bonus Pack provides a number of essential extensions to the Rules framework. The following is a list of the main features:

  • CTools / Page manager integration: Rules Bonus Pack provides a bridge between the Page manager and Rules. It can provide an Event for viewing each custom page variant, which is useful when using Panels and Rules together.

    Rules Bonus Pack also provides integration with the Page manager's Access control feature. We can create condition components that can be used by the Page manager to determine whether a user can access the custom page.

  • Blocks and Theme related Actions: Rules Bonus Pack provides various Block and Theme related Actions. By enabling Rules Bonus: Block and Rules Bonus: Theme modules, we get access to various Actions, such as, placing a block in a region based on a condition or adding a custom CSS class to the body.

These recipes target developers who wish to extend Rules with their own custom Events, Conditions, and Actions. We'll also learn how to provide new entity tokens for Rules to use, how to execute rule configurations in code, and how to provide default rule configurations in our custom module.

The code snippets in these recipes are for demonstration purposes only. They are intended only to explain a specific hook or functionality and do not always provide a generic solution to a problem.

Providing new Events, Conditions, and Actions (Become an expert)


This recipe explains how to create our custom Events, Conditions, and Actions.

In this example, we'll act on a view that's being rendered on the site. We'll create a new condition, where we set the view that's being rendered, and in our action, we'll update a custom database table with the number of times the view has been rendered.

Getting ready

Enable the Views and Views UI modules, and create a view of the latest content on the site. In this example, we'll use the latest content as the view name, and create a block displaying the latest content by the admin that lists all new content posted by user 1.

We also need to create a new database table where we'll store the information; we'll call it custom_view_render. We use hook_schema() in our .install file so our custom table will be available in all supported database engines automatically.

How to do it...

  1. Create a new custom module with the following structure:

    {modules_folder}/custom/
     custom.info
     custom.module
     custom.rules.inc
     custom.install
  2. Define the module's information in the custom.info file:

    name = Custom
    description = Provides an integration with the Rules framework to store the number of times a view was rendered
    core = 7.x
    package = Rules Custom
    dependencies[] = rules
    dependencies[] = rules_admin
    dependencies[] = views
    dependencies[] = views_ui
  3. Define our custom database table in the custom.install file:

    /**
     * Implements hook_schema()
     */
    function custom_schema() {
      $schema['custom_views_render'] = array (		
        'description' => 'The base table for custom views render.',
        'fields' => array(
          'view' => array(
            'description' => 'The name and display ID of the view.',
            'type' => 'varchar',        
            'length' => '32',
            'not null' => TRUE,
            'default' => '',
          ),
          'rendered' => array(
            'description' => 'The number of times the view was rendered.',
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,       
          ),      
        ),       
        'primary key' => array('view'),
      );
      return $schema;
    }
  4. Define our new custom Event in custom.rules.inc:

    /**
    * Implements hook_rules_event_info()
    * Define our new custom event for Rules
    */
    function custom_rules_event_info() {
      return array(
        'custom_views_render' => array (
          'label' => 'A view is rendered',
          'group' => 'Rules Custom',
          'variables' => array(
            'view' => array(
              'type' => 'custom_view_datatype',
              'label' => t('View being rendered')
            )
          )
        )
      );
    }
  5. Because views are not regular data types natively available to Rules; we provided the custom_view_datatype type as the variable type. We also need to define this new data type in our hook_rules_data_info() function:

    /**
     * Implements hook_rules_data_info().
     * This hook should be used to define new data types to Rules.
     *
     * In this case, we simply pass on the view object to Rules
     */
    function custom_rules_data_info() {
      return array(
        'custom_view_datatype' => array(
          'label' => t('view')			
        ),
      );
    }
  6. We want Rules to invoke our event when a view is being rendered, so we'll use hook_views_pre_render() in custom.rules.inc and use rules_invoke_event_by_args() function to notify Rules that the event needs to be invoked:

    /**
     * Implements hook_views_pre_render()
     * Invoke our custom event when a view is being rendered
     */
    function custom_views_pre_render(&$view) {
      rules_invoke_event_by_args('custom_views_render', array($view));
    }
  7. Define our new Condition, that will compare a rendered view's name and display ID with a specified view:

    /**
    * Implements hook_rules_condition_info()
    */
    function custom_rules_condition_info() {
      return array(
        'custom_views_condition' => array(
          'label' => t('View being rendered'),
          'parameter' => array(
            'view' => array(
              'type' => 'text',
              'label' => t('View and display'),
              'options list' => 'custom_views_list',
              'description' => t('Select the view and display ID'),
              'restriction' => 'input',
            ),
          ),
          'group' => t('Rules Custom')
          )
      );
    }
  8. In the options list attribute, we define a custom function custom_views_list that returns an array of the available views on our site:

    /**
     * Helper function that returns all available views on our site
     */
    function custom_views_list() {
      $views = array();
      foreach (views_get_enabled_views() as $view_name => $view) {
        foreach ($view->display as $display_name => $display) {
          $views[$view_name . '-' . $display_name] =
          check_plain($view->human_name) . ' - ' . check_plain($display->display_title);
        }
      }
      return $views;
    }
  9. The array key custom_views_condition, defined in our custom_rules_condition_info() function, will be used to execute the actual comparison that will return a Boolean value, so we'll add a function with the same name:

    /**
     * Callback function for our custom condition
     * The function name must match the array key defined in hook_rules_condition_info()
     */
    function custom_views_condition($view = array()) {
      $current_view = views_get_current_view();
      $parts = explode('-', $view);
      if (($parts[0] == $current_view->name) && ($parts[1] == $current_view->current_display)) {
        return TRUE;
      }
      return FALSE;
    }
  10. Let's create our custom Action for Rules:

    function custom_rules_action_info() {
      return array(
        'custom_update_table' => array(
          'label' => t('Update "custom_views_render" table'),
          'parameter' => array(
            'view' => array(
              'type' => 'custom_view_datatype',
              'label' => t('Rendered View'),
            ),
          ),
          'group' => t('Rules Custom')
          ),
      );
    }
  11. We also need to add a function that actually gets called by Rules when the action fires. The name of this function must match the value of the "base" attribute defined in hook_rules_action_info():

    /**
     * The database function that gets called by the Rules Action
     * The function name must match the value in the 'base' attribute
     * defined in hook_rules_action_info()
     */
    function custom_update_table($view) {
        if (!is_object($view)) {
          return FALSE;
        }
        $result = db_select('custom_views_render', 'c')
          ->fields('c')
          ->condition('view', $view->name .'_'. $view->current_display, '=')
          ->execute()
          ->fetchAssoc();
    
        if ($result) {
          $update = db_update('custom_views_render')
          ->expression('rendered', 'rendered + :one', array(':one' => 1))
          ->condition('view', $view->name .'_'. $view->current_display, '=')
          ->execute();
        }
        else {
          $insert = db_insert('custom_views_render')
          ->fields(array(
            'view' => $view->name .'_'. $view->current_display,
            'rendered' => 1
          ))
          ->execute();
        }
    }

    The last step is to create a new rule configuration, set the Event to Rules Custom | A view is rendered, add a Condition Rules Custom | View being rendered and set it to our latest content view, and add an Action Update "custom_views_render" table:

  12. Set the Event.

  13. Add the Condition.

  14. Set the view and display ID in the Condition, as shown in the following screenshot:

  15. Add our custom Action:

  16. Set the rendered view's Data selector value to the view object provided by our event:

How it works...

In this example, we're creating a custom workflow by providing a new Event, Condition, and Action. In this virtual example, we want to track how many times a given view has been rendered. First we create a new database table to store the data in. Then we define our custom Event (A view is rendered) and our Condition (View being rendered) where we can choose the view and display that's being rendered. In the last step, we define our Action (Update "custom_views_render" table) which takes care of the database operations. Then we go ahead and create the rule configuration using our new Event, Condition, and Action.

It is the best practice to add all Rules hooks to a custom *.rules.inc file. Rules will automatically detect this file and fire the hooks.

There's more...

The following sections provide more information on creating Events, Conditions and Actions, and clearing caches.

Events

To create new Events for Rules, we need to implement hook_rules_event_info(). In this hook we need to return an array of Events, with the keys becoming the machine readable names of the Events. We can define the label, group, and variables this event will use. We can then fire this event by using rules_invoke_event() or rules_invoke_event_by_args() in another function or hook.

Conditions

We can define new Conditions by implementing hook_rules_condition_info(). Again, we need to return an array of Conditions with the array keys becoming the machine readable names of the Conditions, and by default, Rules will look for a function with the same name which will be fired when the Condition is invoked. Therefore, we need to create a function using the same machine readable name.

We must also define the parameters used by the condition. These parameters will be used in the custom function that returns either TRUE or FALSE.

Actions

When defining new Actions, we need to implement hook_rules_action_info(). Actions have a similar structure to Conditions, the definition consists of an array with information about the Action and a callback function that gets fired. The main difference is that an Action may execute an operation or return additional data for Rules.

Clearing the caches

Rules and the Entity API uses a fair amount of caching in order to increase performance. Therefore these caches need to be cleared every time a new Event, Condition, or Action is defined.

Providing new entity tokens (Become an expert)


This recipe demonstrates how to provide new entity tokens for Rules. Entity tokens provides a way to use placeholders in Rules (and other modules) and dynamically replace them with chunks of data.

In this example, we'll provide the current number of registered users on our site as a globally available token for Rules.

How to do it...

  1. Implement hook_entity_property_info() to provide our new entity token:

    /**
     * Implements hook_entity_property_info()
     * We extend the natively available 'site' properties
     */
    function custom_entity_property_info() {
        $info = array();
        $properties = &$info['site']['properties'];	
        $properties['registered_users'] = array(
          'label' => t("Number of registered users"),
          'type' => 'integer',
          'description' => t("Returns the current number of registered users on the site."),
          'getter callback' => 'custom_number_of_users'
        );
        return $info;
    }
  2. We've defined custom_number_of_users as the callback function in the getter callback property, so we'll create this function:

    /**
     * Callback function that returns the current number of registered users
     */
    function custom_number_of_users() {
      $result = db_query("SELECT count(*) FROM {users} WHERE uid > 1")->fetchField();
      return $result;
    }
  3. The newly created entity token will be available to use in Conditions and Actions in REPLACEMENT PATTERNS:

How it works...

By implementing hook_entity_property_info(), we're providing the Entity API information about our new entity token. The function that returns data needs to be defined in the getter callback property. Implementing this hook makes it possible to use new tokens in the rule configurations, or any other configuration that uses Entity API.

Executing Rules programmatically (Become an expert)


This recipe explains how to execute Actions, Rules, or Rule sets programmatically.

In this example, we'll create a simple component that sends an e-mail to the site administrators and execute this component programmatically.

How to do it...

  1. Add a new action set component, call it Send message to all admins:

  2. Add a new Action, System | Send message to all users of a role.

  3. Select administrators in the ROLES select box:

  4. Enter some text to the SUBJECT text field:

  5. Enter a message and save the component:

  6. Now that we've created our component, we can execute it in our custom module using rules_invoke_component():

    <?php
    rules_invoke_component('send_message_to_all_admins');
    ?>

How it works...

Components can be executed programmatically using the rules_invoke_component() function. The first parameter of the function will receive the machine readable name of the component, followed by any additional parameters that the component requires. This way we can execute complex Actions, Rules, Rule sets, Conditions, or additional plugins defined by other modules.

There's more...

The following section describes the execution of standalone plugins programmatically.

Executing standalone plugins

It's also possible to programmatically execute plugins without combining them into a component. We can, for example, execute a Condition in the following way:

<?php
$condition = rules_condition('user_has_role', array('role' => array('editor')));
$condition->execute($user);
?>

Providing new variables for Actions (Become an expert)


This example explains how to modify existing or provide new variables and data for Rules in Actions.

We'll extend our previously defined action with a new one that provides additional data to Rules after the action is executed. In this case, the data provided to Rules is the number of currently registered users on the site.

Getting ready

This recipe is based on the recipe Providing new Events, Conditions, and Actions (Become an expert) in this book.

How to do it...

  1. Add a new associative array to our hook_rules_action_info() function and instead of "parameters" we'll use the "provides" property:

    'custom_registered_users' => array(
    'label' => t('Get number of registered users'),
        'provides' => array(
          'number_of_users' => array(
            'type' => 'integer',
            'label' => t('Number of users')
          ),
        ),
        'group' => t('Rules Custom')
    )
  2. Create the callback function that returns an array in the format Rules expects it:

    /**
    * Callback function that returns the current number
    * of registered users and returns it to Rules in an
    * array
    */
      function custom_registered_users() {
        $result = db_query("SELECT count(*) FROM {users} WHERE uid > 1")->fetchField();	
        // Return an array for Rules with the array key
        // being the machine readable name defined in the
        // 'provides' property
        return array(
           'number_of_users' => $result
        );
      }
  3. After clearing caches, the newly created action will be available in the list of Actions:

  4. Optionally we can modify the variable's label and suggested machine readable name in the next configuration screen.

Tip

When adding additional Actions our new variable becomes available to Rules. For the purpose of this example, we'll add the Action, System | Show a message on the site and display the results in the MESSAGE field. Note that the created variable doesn't become available as a token, so we need to Switch to data selection and select the variable from the drop-down list.

How it works...

Actions can provide new variables to Rules by making use of the provides property in hook_rules_action_info(). The data structure is almost identical to the way we declare parameters, the only difference is that user input is not allowed. By providing new variables to Rules, we can execute complex functions in an action and then work with their return data while still in Rules.

Providing default rule configurations (Become an expert)


This recipe explains how to provide default rule configurations in code. The advantage of that is that we can keep our configurations in code and use version control, such as, SVN or Git.

How to do it...

  1. In our custom module's folder, we add a new file called custom.rules_defaults.inc and declare the rule configuration by implementing hook_default_rules_configuration(). The contents of the file are as follows:

    /**
    * Implements hook_default_rules_configuration()
    */
    function custom_default_rules_configuration() {
      $rule = rules_reaction_rule();
      $rule->label = 'Default Rule';
      $rule->active = TRUE;
      $rule->event('node_insert')
      ->condition('data_is', array('data:select' => 'node:type',       'value' => 'article'))
      ->condition(rules_condition('data_is', array('data:select' =>       'node:author:uid', 'value' => 1))->negate())
      ->action('drupal_message', array('message' => 'Hey [node:author], thanks for creating a new article!'));
    
      $configs['custom_default_rule'] = $rule;
      return $configs;
    }
  2. After clearing the caches, our newly created default rule will become available in the list of configurations, as shown in the following screenshot:

How it works...

Using hook_default_rules_configuration(), we can define our rule configuration in code using Rules' methods for Events, Conditions, and Actions. Rules will look for a file *.rules_defatuls.inc in our module's folder, and automatically add our default rule to the available configurations after clearing the caches.

There's more...

Rules is compatible with the Features module, which provides a centralized API for exporting and importing configuration from the database. This is also an effective way to manage configuration in code and version control systems.

Altering default rule configurations

It is also possible to modify a default rule configuration in code. For that we could use hook_default_rules_configuration_alter() in our *.rules_defaults.inc file.

  /**
   * Implements hook_default_rules_configuration_alter()
   */
  function custom_default_rules_configuration_alter(&$configs) {
    $configs['custom_default_rule']->condition('data_is', array('data:select' => 'node:is_new', 'value' => TRUE));
  }

Making changes to the configuration on the UI

Rules tracks the state of a Rule configuration that has been added programmatically. What that means is that it can determine whether an imported configuration is in its default state (not modified compared to the code) or overridden (modified using the UI, but not in code). When a configuration is modified, Rules allows to revert it back to its original state.

By clicking on that, we're telling Rules that it should re-read the configuration that we've defined in code and revert it to its original state.

Left arrow icon Right arrow icon

Key benefits

  • Learn something new in an Instant! A short, fast, focused guide delivering immediate results.
  • Leverage the power of Rules and Views Bulk Operations
  • Re-use configurations using Components
  • Create your own Events, Conditions and Actions.

Description

Rules is what every Drupal site builder and developer has to use when creating event ñ action-based applications. The framework provides a highly flexible way to create sophisticated, condition-based functions any Drupal based system into an interactive application. Rules makes Drupal rule the CMS world."Drupal Rules How-to" is a practical, hands-on guide that provides you with a number of clear step-by-step exercises, which will help you take advantage of the real power of the Rules framework, and understand how to use it on a site builder and developer levelThis book demonstrates the power and flexibility of the Rules framework. It discusses the main aspects of the module both from the site builder and developer perspective, from basic and advanced Rule configurations using Events, Conditions, Actions and Components to getting familiar with the Rules API. You will also learn how to use additional modules together with Rules to further extend the possibilities of your Drupal system, such as Rules Scheduler to schedule the execution of your Rule configurations and Views Bulk Operations to execute Rule configurations on a view result list. The book also demonstrates the main API features that enable you to create your own Events, Conditions and Actions, provide new data types to Rules and execute your configurations programmatically

Who is this book for?

This book is for Drupal site builders and developers who want to take full advantage of the Rules framework's power and flexibility. Readers of this book should be familiar with the Drupal 7 user interface

What you will learn

  • Getting familiar with the user interface
  • Creating reaction rules using Events, Conditions and Actions
  • Re-using configurations using Components
  • Debugging Rule configurations
  • Using Loops and Lists
  • Extending Rules using other modules like Views Bulk Operations and Flag
  • Creating your own Events, Conditions, and Actions
  • Executing Rule configurations programmatically
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 23, 2012
Length: 74 pages
Edition : 1st
Language : English
ISBN-13 : 9781849519984
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Nov 23, 2012
Length: 74 pages
Edition : 1st
Language : English
ISBN-13 : 9781849519984
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 25.99
Drupal Rules How-to
$25.99
Total $ 25.99 Stars icon

Table of Contents

1 Chapters
Drupal Rules How-to Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(5 Ratings)
5 star 40%
4 star 40%
3 star 20%
2 star 0%
1 star 0%
dkrockville Dec 18, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Drupal 7 is a key Open Source platform for hundreds of thousands of web sites, and the Rules module is one of those things that makes websites highly functional. The book is targeted to Drupal developers wanting to change the way that Drupal handles events and add capabilities not included in the Drupal core. Coverage starts with simple add-ons, like displaying a message after an event occurs, such as adding a new node, or sending a notification after someone has commented on a blog post. The book addresses the many aspects of rules that give them their power, like scheduling and looping.The "how to" style I find easy to work with. Title and summary explanation; Getting ready (what needs to be installed to do this task); How to do it... step by step with screenshots that are quite legible; How it works--summarizing what was accomplished; and finally, There's more provides additional relevant information.There are even some expert How to's, such Executing Rules programmatically.This book is only 60 pages and feels thin, but it really has focus on specific things you can do with the Rules module, along with its cousins: Rules UI, Rules Scheduler, Views, Flag, Views Bulk Operations and Rules Bonus Pack.The author, Robert Varkonyi, knows his stuff. I learned some great recipes that use rules. Recommended!
Amazon Verified review Amazon
Evolving Knowledge Jan 12, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
After working with WordPress for years, I finally made the leap to Drupal to overcome WP's limitations. Switching from WP to Drupal is somewhat like going from a single engine Cessna to a Lear jet; the capabilities of Drupal are beyond imagination.As powerful and dynamic as Drupal is there is an expectation that you have enough experience to grasp the finer subtleties of manipulating content using Rules. It's even difficult to explain the power of Rules because to define it is to limit it. The problem is that the choices are overwhelming."Drupal Rules How-to" is a book that I've looked forward to for some time because it helps tame the beast. Not being a programmer, I recognized my limitations when it came to Rules. What I needed was a step-through of the procedures and available options. Fortunate this book didn't disappoint.Want to know how to trigger an email when someone post, or comments, or registers, or ???, then Rules will get you there. Want a particular type of post to be sticky, again Rules is the way. This doesn't even begin to scratch the potential of Rules.The book may be thin, but it is big on showing you how to get the most from Rules.
Amazon Verified review Amazon
Edward S Wall Jan 05, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I needed this book
Amazon Verified review Amazon
Gregg Marshall Jan 25, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
If you are a Drupal site builder, defined as someone who installs and configures some of the thousands of contributed modules but doesn't program custom modules, then Rules lets you define "if this happens, then do this" actions on your site.It's a relatively short book. While I doubt anyone is going to read it like a novel, it wouldn't take more than a couple of hours.It's organized as a series of how to's, or recipes, on how accomplish various tasks. It's odd the book title didn't carry the cookbook moniker that other Packt books for Drupal have. Each task builds in complexity, starting with a very simple "Hello it's Monday" message through rules that build lists of people and sequence through them sending customized emails.Each recipe is clearly laid out, with explanations followed by screen captures showing how the module should be configured to implement the recipe. It was easy to understand how the various steps fit together.I think it would have been nice to have an overview of the Rules module and how it works. Actually that is one of the areas where the documentation on drupal.org is very well done.Most chapters have a section called "there's more" that offer possible expansions of the topic being discussed. I think it would have been more useful for inexperienced site builders if those expansions were turned into similarly complete recipes, I'm not sure that all site builders will be able to take the hints in those sections and use them without considerable trial and error.The last third of the book is targets at Drupal developers, who write custom modules in PHP. While that part of the book does a decent job of documenting the API and various hooks that are available to allow a developer to extend Rules, it tends to only show the generic hook code, not a specific use of it. I would have liked to see an example that showed how a specific sample module would look.Bottom line is, if you are going to use Rules, you should buy and read this book. It is inexpensive and will save you many times its cost in trying to figure out how to use this very flexible and powerful module.
Amazon Verified review Amazon
Cliff Freeman Sep 25, 2013
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
There's really three sections to this book. The first half of the book covers the first section, it shows how to use rules to do some pretty basic tasks, such as sending an email to the system admin when a new user registers. Honestly, nothing here that you couldn't figure out for yourself or search online for pretty quickly. Editing is very uneven and it took me longer in some cases to understand the books directions that it would have to figure it out on my own. One thing that would have been nice is a table that listed all the configuration options that Drupal provides for rules with a thumbnail explanation, this book only covers a handful and many of the options are not self-explanatory.The third quarter of the book consists of some examples of how to extend Rules with some php code snippets, and how to use Rules in conjunction with the Flags and Views Bulk Operations. Things fall apart a little bit here: explanations don't go into nearly enough depth and I couldn't get a couple of the examples to work. One of them was because the Drupal interface had changed from the time the book had been written (a not too uncommon occurrence) with no obvious work around, but the other case I suspect was just poor editing.The last quarter of the book covers extending rules by adding some non-trivial PHP code additions. I just skimmed this as it isn't something I'm currently interested in, but it looks like explanations are a little lacking here as well.Two and half stars, rounded up to three.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon