Friday, June 6, 2014

Bulding a custom token for url aliases (or anything else)

Tokens are a great resource in Drupal when it comes to creating url aliases, replacing text in emails, creating Rules actions or pretty much anything when it comes to automation.

Here's how to create a custom token for nodes that will perform an action on a field from the node and return it as a replacement.

We start out by informing Drupal that we provide a token applicable to nodes. You can replace node with any entity bundle name to provide tokens for them.

/**
 * Implements hook_token_info().
 * Provides Drupal with a list of our tokens to present in the UI 
 */

function example_token_info() {
  $info = array();
  // Define a new token for nodes.
  // "node" can be replaced with other entity names
  $info['tokens']['node']['reverse'] = array(
    'name' => t('Reverse category term name'),
    'description' => t('Outputs a reversed term name.'),
  );
  // Any other tokens follow here
  return $info;
}

We continue by implementing the hook_tokens method to provide methods for performing the token replacements.

/**
 * Implements hook_tokens() .
 * Takes care of the actual replacement of the token
 */
function example_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'node') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'reverse':
          // Load field from node.
          $fielditems = field_get_items('node',$data['node'],'field_category');
          if ($fielditems[0]['value']) {
            // Load the term.
            $term = taxonomy_term_load($fielditems[0]['value']);            
            // Replace placeholder with reversed term name.
            $replacements[$original] = strrev($term->name);
          }
          else {
            // No category assigned, replace with ''.
            $replacements[$original] = '';
          }
          break;
      }
    }
  }
  // All done.
  return $replacements;

}

That's it. You are now replacing tokens like nobody's business.

No comments:

Post a Comment