The Tiny Book Of Rules - Drupal

Transcription

TheTinyBookofRulesTiny Drupal Books #1Creative commons License

The Tiny Bookof RulesThis is RulesThis book was written by Johan Falk (Itangalo)with the help of Wolfgang Ziegler (fago),and layout by Leander Lindahl (leanderl).It is available under Creative Commons license OfRulesFeel free to use, study, share and improve.Published in March 2012Rules is a module usually used to automateactions on your Drupal site. Rules can reacton events occurring on your site – such as auser logging in or a node being created – andperform customized follow-up actions such asredirecting to a certain page or setting fieldvalues. Optionally, Rules can evaluate conditions before executing any actions.Rules is also a framework to use by othermodules, allowing them to evaluate user-configured Rules components, such as action andcondition sets, or expose data about variablesand entities to other parts of Drupal.3

Rules in site buildingUsing actionsRules actions are reactions that Rules mayperform. Some actions return new data thatRules can work with – such as loading the mostrecent comment written by a user – but mostactions only deal with the data already available to Rules.Some common actions are: Add a variable: This adds a new variable intoyour configuration, which then can be manipulated and used. Calculate a value: This allows you to performbasic arithmetics with numbers. Create a new entity: This asks for requireddata for an entity, and then creates it. Fetch entity by id: This allows for fetchingnodes and other entities by id. Fetch entity by property: This allows for fetching all entities matching selected criteria, forexample a selected field value.5

Show a message on the site: This displays anon-site message. Publish/unpublish content. Create or delete any URL alias. Send an e-mail. Set a data value (described below).Actions can be combined in chains, which allows for rules loading new objects and thenacting on them. Contributed modules may provide more actions to Rules.Data in RulesActions, and other plugins in Rules, act onspecified data types. These data can be simple,such as text, integers and dates; or complexlike nodes – which in turn have properties represented by data, such as node id (integer), title(text), or creation date (date). Complex datatypes may have properties which are complex,too – each node has, for example, an authorrepresented by a user account (which in turnhas a number of properties).Some properties are writable, which meansthat you can alter these with Rules actions. Theaction Set a data value is particularly useful,and can be used to set any writable data.For most action parameters, it is possible toswitch between direct input, meaning manually written input, and data selection, a toolfor drilling down into the nested properties ofcomplex data types.The data object site is always available in Rules,containing global site data such as the accountfor the acting user, the site name, and someother information.67

Finally, it should be noted that field values areread- and writable only if Rules can be certainthat the relevant entity has that field. If working with a node, for example, a field will onlyappear if conditions have been set that limitsthe rule to selected content types. (See usingconditions for more information.) If the entitydoesn’t have separate bundles – such as users –Rules can access the fields right away.Using eventsRules provides a number of events – places ina Drupal page load that can be used to fire offactions. Rules that trigger on events are calledreaction rules (in contrast to stand-alone rulecomponents that must be triggered by othermeans – see the section about components).Each event may provide some associated variables, which can be used in the rule configuration. For example, the event After saving newcontent provides the saved content as a nodevariable while After updating existing contentprovides both the updated and original contentas variables – thereby allowing comparison between the two.8A reaction rule may have more than one triggering event. If they provide different variables, only the variables provided by all eventsmay be used in the configuration, assuring thatthe rule may be evaluated properly regardlessof which of the events is acting as trigger.Using conditionsWhen a reaction rule is fired, or in other occasions where rules are used, you have theoptions to check a number of conditions andabort any actions if the conditions aren’t met.Conditions can be pretty specific, such as Content is promoted to front page, Data value isempty or the comparison between two textstrings – but the most used condition is calledData comparison. This one is used to comparetwo variables available to Rules, or to comparea data variable to a manually entered value– for example to check if a field has a certainvalue or if the node author is the same as theacting user.Conditions can be logically grouped to createand and or groups. These groups may in turncontain other logical groups.9

There are two conditions that are particularlyimportant when working with fields: Content isof type and Entity has field. These conditions allows Rules to know that an entity has a particular field, and subsequently makes the field dataavailable in configuration. The condition Entityis of type has a similar role to provide entityspecific data, but is used much less frequently.(You can also use the Data comparison condition to check the entity bundle.)The most useful thing with lists, though, is theability to loop through them. By adding a loopto your set of actions, you have each actioninside the loop being evaluated once for everyitem in the list you select. This can for examplebe used to send an e-mail to all users in a multiple-value user reference field.It is possible to use loops within loops, thoughyou should be aware that evaluation may become performance heavy if there are manyitems to loop overLists and loopsEach data type declared to Rules automatically gets a sibling data type, being a list of thisparticular data. Thus, Rules cannot only handlenodes, text strings and dates, but also lists ofnodes, strings and dates. This is very usefulwhen working with multiple-value fields, butalso for a few multiple-value entity properties,such as the roles of a user.Rules provides a few actions and conditionsthat are handy when working with lists: List contains item, Add a value to a list and Remove avalue from a list. The latter two can for examplebe used to add/remove a user from a multiplevalue user reference field.10ComponentsReaction rules are the simplest and usuallymost common Rules configurations. But youcan also create Rules components – re-usablecondition sets, action sets, single rules or setsof rules. These components can then be calledby reaction rules, saving you the work of repeating the same conditions in three differentreaction rules.Apart from avoiding repetitive work, components may also be invoked by other modules.Views Bulk Operations, for example, can makeuse of Rules components as actions; Rules11

Scheduler can schedule the evaluation of anycomponent for a future point in time; and withthe help of Rules Bonus Pack, CTools can usecondition components as access plugins inmodules like Page manager and Panels.Components are mainly created and edited likereaction rules – but they have no triggers. Theyalso have configurable variables that are eitherparameters or provided (or both). Parametersare required input data for the component– variables that have to be specified when calling the component. Provided variables are returned to the caller after evaluation.Components are very useful both in site building and coding.Useful additional modulesThere are a number of modules taking advantage of Rules as a framework, or providing newactions, conditions and plugins. The most notable are: Rules Scheduler. This module is included inthe Rules project, and allows scheduling components to be evaluated at a future point in12time. The module can for example be used toschedule content deletion, upgrading of useraccounts, or managing recurring e-mails. Views Bulk Operations (VBO). This moduleextends Views and allows users to performactions on selected rows. Apart from somebase-level actions, Rules components maybe used as actions by VBO. An equally usefulfeature of VBO is that it allows calling Viewsfrom Rules configuration, to load a list of entities listed by Views. Rules Bonus Pack. This module serves as anexperimental lab for new Rules functionality, and provides a number of new actionsand conditions. It also allows using conditioncomponents as CTools access plugins, as wellas providing a new component type used forvalidating and modifying arguments (contextual filter values) in Views. Rules Link. This module can be used to attachlinks to entities, and firing rule sets whenthese links are clicked. Links can also be rendered using Views, and link visibility can becontrolled by condition sets.13

Debugging Rules configurationCoding for RulesRules is to a great tool for automation configured in a point-and-click web interface. Just aswhen automating things with code, you willbe happy for a debugger every once in a while.The Rules debugger is found at the Rules configuration page – you will want to write outthe debug messages directly on the web pagesto easily follow what rules are executed, whatconditions are evaluated TRUE or FALSE, andhow long time each step takes.Normally, extensions of Rules are put into thefile mymodule.rules.inc. This way, the file isonly loaded when Rules is actually used on apage load, which is good for performance. Inthis section of the book, all code examples assume that your module is called mymodule.If variables are not behaving as you expect, youwill find the Rules action Debug value useful(provided by the Devel module). It prints outa krumo dump of a variable that you choose,making it available for inspection.The following sections only contain the verybasics of extending Rules. More detaileddocumentation can be found at the onlinedocumentation (http://www.drupal.org/node/878720) and in rules.api.php included inthe Rules project.Writing conditionsConditions are the least complex Rules extension. To provide new conditions to Rules, youneed two things – a function returning TRUE orFALSE, and an implementation of hook rulescondition info() to tell Rules about your condition. The info hook should return an array onthe following form:1415

conditions array(‘mymodule rules condition check a nodevalue’ array(‘group’ t(‘My module’),‘label’ t(‘My condition’),‘parameter’ array(‘var 1’ array(‘type’ ‘node’,‘label’ t(‘Condition parameter 1(node)’),),‘var 2’ array(‘type’ ‘text’,‘label’ t(‘Condition parameter 2(text)’),),),);),return conditions;The outermost key in the array above is by default the name of the callback function for thecondition – more than one condition can bedeclared by adding more keys. As usual, makesure to prefix your functions with your modulename. Especially note the property parameter,used for telling Rules which type of data thecondition uses as input. There can be any num16ber of parameters – including none – for a condition callback. These are used by the callbackfunction, which returns TRUE or FALSE:function mymodule rules condition check anode value( var 1, var 2) {// Condition logic goes here.return result;}Writing actionsConditions are very similar to conditions intheir structure: a function carrying out theaction, and an info hook implementation totell Rules about it – in this case hook rules actions info(). An important difference is thatwhile conditions return TRUE or FALSE, actionsmay return new data objects to Rules. See example below. actions array(‘mymodule rules action fetch user recentcontent’ array(‘group’ t(‘My module’),‘label’ t(‘My action’),‘parameter’ array(‘var 1’ array(‘type’ ‘user’,17

‘label’ t(‘Fetch latest contentfrom this user’),‘save’ TRUE,),),‘provides’ array(‘var 2’ array(‘type’ ‘node’,‘label’ t(‘Most recent content’),),),);),return actions;Especially note the provides property, describing the variable(s) returned from the action.When writing the action callback, make sure itreturns an array containing the variable(s) thatRules expects. The keys for the return arraymust match the keys in the info hook. The saveproperty for the var 1 parameter means thatRules saves the passed variable if the actionwas successfully executed. Rules will normallywait with saving the changed entities and otherdata until execution is finished, to avoid multiple saves.18function mymodule rules action fetch userrecent content ( var 1) {// Code to fetch a node object goes here.}return array(‘var 1’ account,‘var 2’ node,);Declaring and invoking eventsEvents are declared with an info hook – hookrules event info() – very similar to the previousones. An important difference is the key usedto declare event variables: events array(‘mymodule rules event id’ array(‘group’ t(‘My module’),‘label’ t(‘My event’),‘variables’ array(‘var 1’ array(‘type’ ‘node’,‘label’ t(‘Node provided by theevent’),),),);),return events;Events are not invoked by their own callbacks.19

Rather, they are invoked by adding the rules invoke event() function somewhere in the execution cycle. The first parameter used with thisfunction is the name of the event to call, andany subsequent parameters are being passedas variables to the Rules event:// Placed in your custom module to react inthe execution cyclerules invoke event(‘mymodule rules event id’, node);An alternative to rules invoke event is therules invoke event by args() function. It takestwo parameters only, the first being the nameof the event and the second being an array ofvariables to pass to the event.Invoking componentsprogrammaticallyRules components are handy tools for allowing site builders to customize their own actionsand conditions. If you are writing a module thatallows site builders to set custom conditions(or actions), you can let them set these up asRules components and then evaluate selectedcomponents programmatically. This works ina way analogous to invoking events, by usingrules invoke component().The first argument is the (machine) name ofthe component, and any subsequent arguments are variables sent to the component.// Included somewhere in your custom module. component name settings[‘rules component name’];// Any variables provided from the componentare returned from its evaluation. result rules invoke component( componentname, var 1, var 2);2021

Extending and alteringdata typesample shows how a site-wide list of blacklistedwords can be added to the site variable, to beused in Rules configuration.Rules relies on information from the Entity APImodule to declare data types for each entityon your site. These are complemented by anumber of other data types, which are (withmachine names in parenthesis): date, decimalnumber (decimal), duration, formatted text(text formatted), integer, text (text), text token (token), truth value (boolean), URI (uri) andwatchdog log entry (log entry). As previouslymentioned, all data types and known entitytypes are also represented by lists being arraysof the data values.function mymodule entity property infoalter(& info) { info[‘site’][‘properties’][‘mymodule blacklisted’] array(‘type’ ‘list text ’,‘label’ t(‘Blacklisted words’),‘description’ t(‘Disallowed words onthe site’),‘getter callback’ ‘mymodule get blacklisted words’,);}The formatted text, watchdog log entry and allentities are complex data types, having a number of properties – each property being oneof the declared data types. These propertiescan be altered and extended by modifying theproperties array for the data type with help ofhook entity property info alter() and hookrules data info alter().function mymodule get blacklisted words() {return variable get(‘mymodule blacklisted’,array());}It should be noted that the globally availabledata is made available under the key site foundin hook entity property(). The following ex2223

Providing new entities anddata typesJust as existing data types can be altered, newones can be added. This is done by implementing hook rules data info(). An example of thisis displayed below, where views are being introduced as a data type in Rules.Function mymodule rules data info() { data types array(‘mymodule view’ array(‘label’ t(‘view object’),‘wrap’ TRUE,‘property info’ array(‘machine name’ array(‘type’ ‘text’,‘label’ t(‘Machine name’),),‘args’ array(‘type’ ‘list text ’,‘label’ t(‘Arguments’),‘setter callback’ ‘entity property verbatim set’),),}24);),Especially note the wrap property, whichmakes Rules wrap the passed object and makeit available for data selection. It is required forany complex data type. Two properties aredeclared in the property info array, which willmake it possible to read these properties inRules. Also, the args property has a setter callback – meaning that Rules cannot only read butalso write the arguments of the view object.It so happens that the properties’ machinenames correspond directly to properties inthe view object. If this wasn’t the case, a getter callback would have been required to tellRules how to read the property, just as it worksfor entity properties. Now the default callbackentity property verbatim get() is used, whichlike its setter sibling simply writes to the dataobject using the declared machine name asproperty name.New entity types are declared using hook entity info. Its usage is not documented here,but if your entities are declared properly forthe Entity API modules, Rules will know aboutthem too.25

The Tiny Book of Rules is tiny and it’sabout the Rules module for Drupal.Rules is a module usually used to automate actions on your Drupal site. Rulescan react on events occurring on your site– such as a user logging in or a node beingcreated – and perform customized followup actions such as redirecting to a certainpage or setting field values. Optionally,Rules can evaluate conditions beforeexecuting any actions.Rules is also a framework to use by othermodules, allowing them to evaluate userconfigured Rules components, such asaction and condition sets, or expose dataabout variables and entities to other partsof Drupal.Tiny Drupal Books #1Creative commons License28

the following form: Debugging Rules configuration Rules is to a great tool for automation config-ured in a point-and-click web interface. Just as when automating things with code, you will be happy for a debugger every once in a while. The Rules debugger is found at the Rules con-figuration page - you will want to write out