Curated ear

Create a custom token in Drupal 9

Tan Nguyen

|

Creating a custom token in Drupal 9 involves defining a new token using a custom module. Tokens are placeholders that can be replaced with dynamic content when used in various parts of your site, such as in text formats, emails, or node templates. Here's a step-by-step guide to creating a custom token

  1. Create a Custom Module: If you don't already have a custom module, create one. You can create a custom module in Drupal by following these steps:

    a. Create a new folder for your module inside the modules/custom directory in your Drupal installation. Give it a suitable name, such as "custom_tokens."

    b. Inside your module folder, create a custom_tokens.info.yml file and a custom_tokens.module file.

  2. Define Your Token: In the custom_tokens.module file, you'll define your custom token using Drupal's hook_token_info() and hook_tokens() hooks.

/**
 * Implements hook_token_info().
 */
function custom_tokens_token_info() {
  $info = array();

  $info['tokens']['custom']['my_custom_token'] = array(
    'name' => t('My Custom Token'),
    'description' => t('This is a custom token for demo.'),
  );


  return $info;
}




/**
 * Implements hook_tokens().
 */
function custom_tokens_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'custom') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'my_custom_token':
          $replacements[$original] = 'Custom Token Content';
          break;
      }
    }
  }




  return $replacements;
}

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word