Actions: stored procedures for Drupal
Note: this page describes actions for Drupal 5 using actions.module 5.x-1.x. When actions were included in Drupal 6 core, the format for actions changed. You can see the new format here.
The Actions module allows the configuration of Drupal actions. A Drupal action is a specially written PHP function whose parameters are configured through the web. For example, the Send Email action has parameters Recipient, Subject, and Message. You could fill in MrFoo@example.com for the recipient, Hi for the subject, and Hello, Mr. Foo for the message to create an instance of the Send Email action. This action instance could then be fired by a module at appropriate times when you want Mr. Foo to get an email.
Actions are like stored procedures that can be loosely coupled with events in Drupal.
Let's examine a ridiculously simple example. Suppose you want to be draconian with your Drupal site's comment policy. Any user who leaves a comment gets blocked immediately. You can implement this quite easily with the comment hook:
<?php
foo_comment($a1, $op) {
if ($op == 'insert') {
global $user;
// block user here...
}
}
?>What an action does is wrap up this code into a nice package. That package can then be associated with the nodeapi hook. Or some other hook. Actions takes this function, which we'll call "Block current user", and allows you to assign it to any hook-op combination.
We do that by several coding conventions. Here is the skeleton of a simple action:
<?php
/**
* Implementation of a Drupal action.
*/
function action_block_user($op, $context = array(), &$object) {
switch ($op) {
case 'do':
global $user;
// block user here...
break;
case 'metadata':
return array(
'description' => t('Block current user'),
'type' => 'User',
'batchable' => TRUE,
'configurable' => FALSE,
'supported hooks' => array(
'nodeapi' => array(
'delete' => 1,
'insert' => 1,
'update' => 1,
'view' => 1
),
'comment' => array(
'insert' => 1,
'update' => 1,
'delete' => 1
)
)
);
}
}
?>We've implemented two ops. The 'metadata' op describes the action by declaring some things, including what hook/op combinations it supports. The 'do' op is actually where the code runs. We list the 'do' op first in the switch statement for performance, since Drupal will then encounter it first during execution.
The above is a non-configurable action. There's nothing about it you can change. It will block the current user and that's that. It's basically a singleton action.
On the other hand, an action like "Send email" needs to know some things in order to run. It needs a subject, and body, a recipient, and such. Configurable actions are not available for use until they have been configured (obviously). They can be configured from the main actions interface at admin/build/actions.
