Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

(Custom) Token creation for Drupal 7

Parent Feed: 

 Today I had a plan to create tokens for my new module wich will create hashed pdf link for commerce order, becouse it would be really nice to use tokens with rules. So I just looked how it works and wanted to create some simple examples.
I can easily create new token from scratch with these two functions.

/**
 * Implements hook_token_info_alter().
 */
function commerce_order2pdf_token_info() {
  $info['tokens']['commerce-order']['hashed_pdf_link'] = array(
    'name' => t('Hashed link to pdf'),
    'description' => t("Hashed link for pdf generation."),
  );
  return $info;
}
/**
 * Implements hook_tokens().
 */
function commerce_order2pdf_tokens($type, $tokens) {
 if($type = 'commerce-order') {
   $replacements['[commerce-order:hashed_pdf_link]'] = 'my replacement';
 }
  return $replacements;
}

What I really want to do is to add new tokens to my existing tokens and use existing data. So I just had to use hook_token_info_alter and hook_token_alter functions.

/**
 * Implements hook_token_info_alter().
 */
function commerce_order2pdf_token_info_alter(&$data) {
  $data['tokens']['commerce-order']['hashed_pdf_link'] = array(
    'name' => t('Hashed link to pdf'),
    'description' => t("Hashed link for pdf generation."),
  );
  return $data;
}
/**
 * implements hook_tokens_alter().
 */
function commerce_order2pdf_tokens_alter(array &$replacements, array $context) {
  $order = $context['data']['commerce-order'];
  $hash = hash('md5', $order->order_id . $order->created);
  $replacements['[commerce-order:hashed_pdf_link]'] =  l(t('Download order as pdf'),
"order/{$order->order_id}/" . $hash, array('absolute' => TRUE));
}
Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web