Last updated October 16, 2013. Created by NancyDru on September 11, 2008.
Edited by JesseDP, peterx, Dave Reid, VM. Log in to edit this page.

Overview

In many cases, it's useful to allow users to define patterns or large chunks of text that contain programmatically derived values. For example, form email messages addressed to a given user, or URL path aliases containing the title of a given node. Both examples require bits of data that vary each time the text is generated -- node titles, user ids, and so on. Rather than forcing users to embed ugly snippets of PHP, or creating elaborate and bizarre UIs for configuring the patterns via the browser, it's most useful to give users a set of 'placeholder' tokens to place in their text.

Token provides a shared API for exposing and using placeholder tokens and their appropriate replacement values. It does nothing by itself -- other modules can use it to avoid reinventing the wheel.

Using Token Replacement

To apply token replacement to a chunk of text, you have two options. The first, and simplest, is:

token_replace($original, $type = 'global', $object = NULL,
                $leading = '[', $trailing = ']')

$original is the source text to perform substitutions on: it can be either a simple string, or an array of multiple strings.

$type and $object are to be used when performing substitution based on a particular Drupal object. Replacing tokens in an email with values from a particular user account, or replacing tokens in a path alias pattern with values from the node being aliased, are two examples.

$type should contain the general object type (node, comment, user, etc.) while $object should contain the object itself.

$leading and $trailing can be used to override the default token style. For example, to replace tokens using %this style, pass in '%' and '' for the $leading and $trailing values. Note that passing in a leading but NOT trailing value can lead to false positives if two tokens are named in a similar fashion (%node_term and %node_term_id, for example).

Altering The Replacement Values

If your module needs to perform additional cleanup work on the replacement values before doing the actual substitutions (cleaning replacement values to make them appropriate for path aliasing, truncating them to a particular length, etc.) you can manually retrieve the list of tokens and replacement values, then call str_replace() yourself.

token_get_values($type = 'global', $object = NULL)

Pass in the $type and $object as you would with the simpler token_replace() function. The return value will be an object containing one array of tokens and one array of values as in this example:

stdClass Object {
  [tokens] => array(
    [0] => mytoken1,
    [1] => mytoken2
  ),
  [values] => array(
    [0] => value1,
    [1] => value2,
  )
}

Showing available tokens

In some forms that solicit tokens, it is nice to show what tokens are available. This is easily done with theme('token_help', $type). For example:

Drupal 6:

  if (module_exists('token')) {
    $form['view']['token_help'] = array(
      '#title' => t('Replacement patterns'),
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
//      '#description' => t('Prefer raw-text replacements for text to avoid problems with HTML entities!'),
      );
    $form['view']['token_help']['help'] = array(
      '#value' => theme('token_help', 'node'),
      );
  }

Drupal 7:

  if (module_exists('token')) {
    $form['view']['token_help'] = array(
      '#title' => t('Replacement patterns'),
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
//      '#description' => t('Prefer raw-text replacements for text to avoid problems with HTML entities!'),
      );
    $form['view']['token_help']['help'] = array(
      '#theme' => 'token_tree',
      '#token_types' => array('node'),
      );
  }

Providing Placeholder Tokens

Token.module provides a small set of default placeholders for global values like the name of the currently logged in user, the site's URL, and so on. Any module can provide additional tokens by implementing two hooks.

Security note: For tokens which include user input, users and modules
expect to see both a ['token-name'] and a ['token-name-raw'] value.

hook_token_values($type, $object = NULL, $options = array())

This function should return a keyed array of placeholders, and their replacement values. $type contains the current context -- 'node', 'user', 'global', etc. $object contains the specific node, user, etc. that should be used as the basis for the replacements. Only generate and return replacement tokens when $type is something that your module can really deal with. That helps keep things speedy and avoid needlessly
searching for jillions of replacement tokens. The $options array can contain additional options (exact use is dynamic and not easily documented).

For example:

function my_user_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'user') {
    $user = $object;
    $tokens['name']      = $user->name;
    $tokens['mail']      = $user->mail;
    return $tokens;
  }
}

hook_token_list($type = 'all')

This function is used to provide help and inline documentation for all of the possible replacement tokens.

As with hook_token_values, $type indicates the context that token help is being generated for. Unlike hook_token_values however, you should show ALL tokens at the same time if $type is 'all'. As such, the help text should be keyed by the $type context your module will use when doing the actual replacements. For example:

function my_user_token_list($type = 'all') {
  if ($type == 'user' || $type == 'all') {
    $tokens['user']['name']      = t("The user's name");
    $tokens['user']['mail']      = t("The user's email address");
    return $tokens;
  }
}

Examples of more elaborate token replacement setups can be found in the token_node.inc file that's bundled with token.module.

Security Note

If you use any of the tokens in the ['raw'] sub-array then please note that these are unfiltered values which could conceivably contain XSS attacks or other malicious data. Your module should then provide its own filtering to ensure the safety of site users.

Installation

Standard module installation applies.

Settings

None.

Permissions

None.

Menu items

None.

 

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

the document is for drupal 6, not drupal 7, no hook_token_values in drupal 7. the docement is out of date, is there anybody have time to update it ?

blog: http://blog.sky.city.me
wechat id: shinvdu

This page speaks at least a couple of words about how tokens are in Drupal 7. Cheers!

http://takearest.ru - my Drupal baby :)

Not sure if my question related to that Token topic. I am trying to build connection between javascript client and Drupal Services. Just simple log in, log out, create node. The approved solution for that states:
1. POST to /rest/user/login (nothing in headers). Construct the $cookie from session name + id
2. GET to /services/session/token (include $cookie in the headers). Save the $token returned.
3. Include $cookie and $token in the headers of subsequent requests of a logged in user.

I was able to log in and get session id with session name from server. But on step 2 I am getting error: 404 (Not found: Could not find resource session.).
Do I have to use Token module with Services?

My Playgroud:
ВСЁSTUDIO