Add Custom Tokens in Custom Module for Drupal 9

grayscale photography of person holding coin or token

In Drupal 9, you can create custom tokens using the Token API for your custom module. The Token API provides a central API for modules to use to provide tokens. Tokens are placed into text by using the [type:token] syntax, where type is the machine-readable name of the token type, and token is the machine-readable name of the token within the type.

  1. Create a yourmodule.tokens.inc in your custom module directory.
  2. Define your custom token type:
/**
 * Implements hook_token_info().
*/
 
function yourmodule_mailout_token_info() {
  $types['yourtype'] = [
    'name' => t('Your Type'),
    'description' => t('Tokens for Your Module.'),
  ];
  $tokens['yourtoken'] = [
    'name' => t("Your Token"),
    'description' => t('The custom token'),
  ];
  return [
    'types' => $types,
    'tokens' => ['yourtype' => $tokens],
  ];
}
  1. Define the token replacements:
use Drupal\Core\Render\BubbleableMetadata;
 
/**
* Implements hook_tokens().
*/
function yourmodule_mailout_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
 
  if($type == 'yourtype') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'yourtoken':
          $replacements[$original] = 'Your replacement';
        break;
      }
    }
  }
 
  return $replacements;
}
  1. Use your custom token in your module or in any field or text area by adding [yourtype:yourtoken] to the text.

Add new comment

Plain text

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