Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
To display a list of available tokens in your module or code, use the following examples.
Drupal 8
In a form:
$form['tokens'] = \Drupal::service('token.tree_builder')->buildRenderable(['node', 'user']);
// Pass your entity machine name as parameter in an array to add it to the list.
);
Drupal 7
In a form:
$form['tokens'] = array(
'#theme' => 'token_tree_link',
// To get these options to work, use the patch from https://www.drupal.org/node/2289203 if you have Token 7.x-1.5 or earlier.
'#token_types' => array('node'), // The token types that have specific context. Can be multiple token types like 'term' and/or 'user'
'#global_types' => TRUE, // A boolean TRUE or FALSE whether to include 'global' context tokens like [current-user:*] or [site:*]. Defaults to TRUE.
'#click_insert' => TRUE, // A boolean whether to include the 'Click this token to insert in into the the focused textfield' JavaScript functionality. Defaults to TRUE.
);
In a render array:
$form['tokens'] = array(
'#theme' => 'token_tree',
'#token_types' => array('node'),
'#global_types' => FALSE,
'#click_insert' => FALSE,
);
Drupal 6
The parameters to theme('token_tree') are the following in order:
- The array of token types to display.
- A boolean to allow the global token types (defaults to TRUE).
- A boolean to allow the click-insert JavaScript functionality (defaults to TRUE).
In a form:
$form['tokens'] = array(
'#value' => theme('token_tree', array('node'), TRUE, TRUE),
);
In a page output:
$output = ...
$output .= '<h4>Available tokens:</h4>';
$output .= theme('token_tree', array('node'), TRUE, TRUE);
return $output;
Comments
Parameters are not passed to #theme functions in D6
This code:
will always result in default values being received by the theme_token_tree() function in D6. That is because, unlike D7, D6 does not process extra theme parameters starting with #. The workaround is to use theme('token_tree'...) as documented in the "page output" example. Here's a rewritten version: