How to add Token support for Drupal 7

Submitted by Daniel Henry on 05/15/2013 - 02:44:pm

I have to admit I am often frustrated by modules that don’t provide token support. It is just too easy to not include. So here is a little snippet that will get anyone up and running in the token world. Best of all if your concerned whether or not you will need to include the token module as a dependency, this snippet makes the dependency optional. 

Add this code to any form that needs token support to display the tokens the user can use. Just do this in a hook_form_alter() or hook_form_FORM_ID_alter().

  1. // Add to form
  2. // Display the list of available placeholders if token module is installed.
  3. if (module_exists('token')) {
  4.   $form['token_help'] = array(
  5.     '#theme' => 'token_tree',
  6.     '#token_types' => array('node'),
  7.   );
  8.  
  9.   $form['#submit'][] = my_module_form_submit;
  10. }

The user knows what tokens to use so now just make sure their tokens get applied.

  1. function my_module_form_submit($form, &$form_state) {
  2.   // Call token replace on the text field passing args into the second parrameter.
  3.   $form['field_my_field'] = token_replace($form['field_my_field'], array('node' => $form['node']));
  4. }

And voila! Instant token support.

Blog image provided by Lora Rajah