<!DOCTYPE html> <html class="no-js" lang="en-GB"> <head> <title>Creating and using custom tokens in Drupal 7 | Oliver Davies</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta property="og:url" content="https://opdavies.github.io/oliverdavies.uk/blog/2013/02/16/creating-and-using-custom-tokens-drupal-7"> <meta property="og:title" content="Creating and using custom tokens in Drupal 7"/> <meta property="og:image" content="https://opdavies.github.io/oliverdavies.uk/assets/images/me-precedent.jpg"/> <meta property="og:image:height" content="327"/> <meta property="og:image:type" content="image/jpg"> <meta property="og:image:width" content="327"/> <link rel="stylesheet" href="https://opdavies.github.io/oliverdavies.uk/assets/css/main.css"> <link rel="stylesheet" href="https://opdavies.github.io/oliverdavies.uk/assets/css/blog-post.css"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=57" sizes="57x57"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=114" sizes="114x114"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=72" sizes="72x72"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=144" sizes="144x144"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=60" sizes="60x60"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=120" sizes="120x120"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=76" sizes="76x76"> <link rel="apple-touch-icon" href="/assets/images/me-precedent.jpg?s=152" sizes="152x152"> <link rel="icon" href="/assets/images/me-precedent.jpg?s=160" sizes="160x160"> <link rel="icon" href="/assets/images/me-precedent.jpg?s=96" sizes="96x96"> <link rel="icon" href="/assets/images/me-precedent.jpg?s=32" sizes="32x32"> <link rel="icon" href="/assets/images/me-precedent.jpg?s=16" sizes="16x16"> </head> <body class=""> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="https://opdavies.github.io/oliverdavies.uk/">Oliver Davies</a> </div> <div id="navbar" class="collapse navbar-collapse" role="navigation"> <ul class="nav navbar-nav"> <li class=""> <a href="/">About</a> </li> <li class=""> <a href="/experience">Experience</a> </li> <li class=""> <a href="/testimonials">Testimonials</a> </li> <li class=""> <a href="/talks">Talks</a> </li> <li class="active"> <a href="/blog">Blog</a> </li> <li class=""> <a href="/contact">Contact</a> </li> </ul> </div> </div> </nav> <div class="container"> <div class="row"> <main class="col-md-9"> <h1>Creating and using custom tokens in Drupal 7</h1> <p class="posted">16th February 2013</p> <p>This post outlines the steps required to create your own custom tokens in Drupal.</p> <p>When writing the recent releases of the <a href="http://drupal.org/project/copyright_block">Copyright Block</a> module, I used tokens to allow the user to edit and customise their copyright message and place the copyright_message:dates token in the desired position. When the block is rendered, the token is replaced by the necessary dates.</p> <p>We will be using the fictional <em>foo</em> module to demonstrate this.</p> <h2 id="requirements">Requirements</h2> <ul> <li><a href="http://drupal.org/project/token">Token module</a></li> </ul> <h2 id="recommended">Recommended</h2> <ul> <li><a href="http://drupal.org/project/devel">Devel module</a> - useful to run <code>dpm()</code> and <code>kpr()</code> functions</li> <li><a href="http://drupal.org/project/copyright_block">Copyright Block module</a> - 7.x-2.x and 6.x-1.x use tokens, handy as a reference</li> </ul> <h2 id="implementing-hook_token_info">Implementing hook_token_info()</h2> <p>The first thing that we need to do is define the new token type and/or the token itself, along with it's descriptive text. To view the existing tokens and types, use <code>dpm(token_get_info());</code>, assuming that you have the <a href="http://drupal.org/project/devel">Devel module</a> installed.</p> <pre><code class="language-php">/** * Implements hook_token_info(). */ function foo_token_info() { $info = array(); // Add any new tokens. $info['tokens']['foo']['bar'] = t('This is my new bar token within the foo type.'); // Return them. return $info; } </code></pre> <p>In this case, the token called <em>bar</em> resides within the <em>foo</em> group.</p> <p>If I needed to add a new token within an existing token type, such as 'node', the syntax would be <code>$info['tokens']['node']['bar']</code>.</p> <h2 id="implementing-hook_tokens">Implementing hook_tokens()</h2> <p>Now that the Token module is aware of our new token, we now need to determine what the token is replaced with. This is done using <code>hook_tokens()</code>. Here is the basic code needed for an implementation:</p> <pre><code class="language-php">/** * Implements hook_tokens(). */ function foo_tokens($type, $tokens, array $data = array(), array $options = array()) { $replacements = array(); // Code goes here... // Return the replacements. return $replacements; } </code></pre> <p>The first thing to check for is the type of token using an <code>if()</code> function, as this could be an existing type like 'node', 'user' or 'site', or a custom token type like 'foo'. Once we're sure that we're looking at the right type(s), we can use <code>foreach ($tokens as $name => $original)</code> to loop through each of the available tokens using a <code>switch()</code>. For each token, you can perform some logic to work out the replacement text and then add it into the replacements array using <code>$replacements[$original] = $new;</code>.</p> <pre><code class="language-php">/** * Implements hook_tokens(). */ function foo_tokens($type, $tokens, array $data = array(), array $options = array()) { $replacements = array(); // The first thing that we're going to check for is the type of token - node, // user etc... if ($type == 'foo') { // Loop through each of the available tokens. foreach ($tokens as $name => $original) { // Find the desired token by name switch ($name) { case 'bar': $new = ''; // Work out the value of $new... // Add the new value into the replacements array. $replacements[$original] = $new; break; } } } // Return the replacements. return $replacements; } </code></pre> <h2 id="example">Example</h2> <p>An example from Copyright Block module:</p> <pre><code class="language-php">/** * Implements hook_tokens(). */ function copyright_block_tokens($type, $tokens, array $data = array(), array $options = array()) { $replacements = array(); if ($type == 'copyright_statement') { foreach ($tokens as $name => $original) { switch ($name) { case 'dates': $start_year = variable_get('copyright_block_start_year', date('Y')); $current_year = date('Y'); $replacements[$original] = $start_year < $current_year ? $start_year . '-' . $current_year : $start_year; break; } } } return $replacements; } </code></pre> <h2 id="using-token_replace">Using token_replace()</h2> <p>With everything defined, all that we now need to do is pass some text through the <code>token_replace()</code> function to replace it with the values defined within <code>hook_token()</code>.</p> <pre><code class="language-php">$a = t('Something'); // This would use any token type - node, user etc. $b = token_replace($a); // This would only use foo tokens. $c = token_replace($a, array('foo')); </code></pre> <p class="tags"> Tags: <a href="https://opdavies.github.io/oliverdavies.uk/blog/tags/drupal">drupal</a>, <a href="https://opdavies.github.io/oliverdavies.uk/blog/tags/drupal-planet">drupal-planet</a>, <a href="https://opdavies.github.io/oliverdavies.uk/blog/tags/drupal-7">drupal-7</a>, <a href="https://opdavies.github.io/oliverdavies.uk/blog/tags/tokens">tokens</a> </p> <div class="post-pager is-flex"> <div class="is-half"> <a href="/blog/2013/01/09/checking-if-user-logged-drupal-right-way"> « Checking if a user is logged into Drupal (the right way) </a> </div> <div class="is-half text-right"> <a href="/blog/2013/03/02/quickest-way-install-sublime-text-2-ubuntu"> The Quickest way to Install Sublime Text 2 in Ubuntu » </a> </div> </div> <div class="about-author"> <h2>About the Author</h2> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/me-precedent.jpg" alt="Picture of Oliver" class="img-circle"> <p>Oliver Davies is a Web Developer, System Administrator and Drupal specialist based in the UK. He is a Senior Developer at <a href="https://microserve.io">Microserve</a> and also provides freelance consultancy services for Drupal websites, PHP applications and Linux servers.</p> </div> </main> <div class="col-md-3"> <div class="panel badges text-center"> <a class="badge--da-member" href="https://assoc.drupal.org/membership" title="I’m a Drupal Association member."> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/da-individual-member.png" alt="Drupal Association Individual Member" width="152" > </a> <a href="http://drupalcores.com/#opdavies"> <img alt="I built Drupal 8 with hand holding a wrench on blue background" src="https://opdavies.github.io/oliverdavies.uk/assets/images/drupal-8.jpg" /> </a> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/badges/acquia-certified-developer-drupal-8.png" alt="Acquia Certified Developer - Drupal 8 Exam Badge" height="147" width="147" /> <a href="http://conference.phpnw.org.uk/phpnw17"> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/badges/phpnw17.png" alt=""> </a> </div> <div class="availability panel panel-default"> <div class="panel-heading">Availability</div> <div class="panel-body"> <p> <i class="fa fa-thumbs-o-up text-warning"></i> Currently have limited part-time capacity </p> <p> <i class="fa fa-thumbs-o-down text-danger"></i> Currently no spare full-time capacity. </p> </div> </div> <div class="latest-posts panel panel-default"> <div class="latest-posts__heading panel-heading">Latest blog posts</div> <ul class="list-group"> <li class="post list-group-item"> <span class="post__title"> <a href="/blog/2017/06/09/introducing-the-drupal-meetups-twitterbot"> Introducing the Drupal Meetups Twitterbot </a> </span> - <span class="post__date">9th June, 2017</span> </li> <li class="post list-group-item"> <span class="post__title"> <a href="/blog/2017/05/20/turning-drupal-module-into-feature"> Turning Your Custom Drupal Module into a Feature </a> </span> - <span class="post__date">20th May, 2017</span> </li> <li class="post list-group-item"> <span class="post__title"> <a href="/blog/2017/05/15/drupalcamp-bristol-early-bird-tickets-sessions-sponsors"> DrupalCamp Bristol 2017 - Early Bird Tickets, Call for Sessions, Sponsors </a> </span> - <span class="post__date">15th May, 2017</span> </li> </ul> </div> </div> </div> </div> <footer class="container"> <p class="copyright"> © 2010-2017 Oliver Davies. Built with <a href="https://sculpin.io">Sculpin</a>. </p> <div class="meetups"> <h2>Things that I organise</h2> <ul> <li class="meetups--drupal-bristol"> <a href="http://www.drupalbristol.org.uk" title="Drupal Bristol"> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/meetups/drupal-bristol.jpeg" alt="Drupal Bristol"> </a> </li> <li class="meetups--drupalcamp-bristol"> <a href="http://www.drupalcampbristol.co.uk" title="DrupalCamp Bristol"> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/meetups/drupalcamp-bristol.png" alt="DrupalCamp Bristol"> </a> </li> <li class="meetups--phpsw"> <a href="http://phpsw.uk" title="PHPSW"> <img src="https://opdavies.github.io/oliverdavies.uk/assets/images/meetups/phpsw.jpeg" alt="PHPSW"> </a> </li> </ul> </div> </footer> <script src="https://opdavies.github.io/oliverdavies.uk/assets/js/site.js"></script> <script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-11967257-1', 'auto'); ga('send', 'pageview');</script> </body> </html>