18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5<br />

Tokens can also be 'chained'—a token can refer to another token which can refer<br />

to yet another one. As an example, the token [node:author] contains the name<br />

of a node's author, and the token [user:e-mail] contains the e-mail address of a<br />

given user. To retrieve the e-mail address of a node's author, you can chain the two<br />

together with the token [node:author:e-mail].<br />

<strong>Module</strong> developers can also expose their own tokens for other module<br />

developers to take advantage of. For more information on how to expose<br />

tokens in your module, see the following sites:<br />

http://api.drupal.org/api/function/hook_token_info/7<br />

http://api.drupal.org/api/function/hook_tokens/7<br />

<strong>Drupal</strong>'s token system is extremely flexible and prevents site builders and developers<br />

from having to replace information in site text every time it changes. So let's see how<br />

we can use tokens in our module.<br />

How do we know what tokens are available?<br />

<strong>Drupal</strong> 7 does not include a user interface for browsing available<br />

tokens, however the contributed Token module implements a very nice<br />

JavaScript tree-like browser for them. You can download and install it<br />

from the following site:<br />

http://drupal.org/project/token<br />

Additionally module developers can use the function token_info() to<br />

get a structured array containing all the tokens in the system. This can be<br />

parsed and/or displayed as desired.<br />

Implementing tokens in your text<br />

The obvious place where User Warn could use tokens is in the text of the outgoing<br />

e-mails. Let's expand the very simple default text we included above, and also put it<br />

into a constant, for easier module readability and maintainability. This will require<br />

updating some of the previous code, but in the future we will only need to change<br />

this information in one place.<br />

define('USER_WARN_MAIL_TEXT',<br />

'Hello [user:name],<br />

We have been notified that you have posted comments on [site:name]<br />

that are in violation of our terms of service. If this behavior<br />

continues your account will be suspended.<br />

Sincerely,<br />

[site:name]');<br />

[ 147 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!