Skip to main content
Image
Drupal

Create custom tokens in Drupal 8

Hello everyone!

We are going to talk about the tokens provided by the contributed Token module , how useful they are and how to implement them correctly in a simple way in our Drupal project.

What are tokens?

Tokens are a list of 'wildcards' or text fragments provided by the contributed Token module that solve our lives when it comes to displaying messages or dynamic routes, although they also have other use cases. Some examples of tokens can be:

Welcome Jaime, you are user number 134,211 ==> Welcome [user-name], you are user number [node.count]

In the previous case, we can find two tokens . These can be provided by Drupal itself or can be customized.

Custom tokens

Unfortunately, Drupal will not always have all the tokens accessible, since they depend a lot on the context (the current session/page, the content type, view, etc...) This is when we can use custom tokens programmatically.

First of all, we must create a custom module (if we don't already have one) to later work on the mymodule.module of our project.

In this example, we will create a token that will give us the type of currency that the current logged in user has selected. First of all, we implement the token info hook, which will give a name, description and machine name to the token that we are going to create.

/**
 * Implements hook_token_info().
 */
function mymodule_token_info() {
  $info = [];
  $info['types']['custom_token'] = ['name' => t('Custom tokens'), 'description' => t('My module c
  ustom tokens')];
  $info['tokens']['custom_token']['current_user_currency'][] = 'Provides the user's currency';
  return $info;
}

Next, we will use the hook_tokens to apply the desired logic. What we will do is make a simple query to the database to obtain the currency of the current user.

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'custom_token') {
    foreach ($tokens as $name => $original) {
      // Find the desired token by name.
      switch ($name) {
        case 'current_user_currency':
          $current_user = User::load(\Drupal::currentUser()->id());
          $connection = \Drupal::database();
          $query = $connection->select('users', u);
          $query->condition('u.uid', $current_user->id(), '=');
          $query->fields('u', ['currency']);
          $result = $query->execute() == 'EUR' ? 'EUR' : 'USD';
          $replacements[$original] = $currency;
          break;
      }
    }
  }
  return $replacements;
}

Once we clear caches (drush cr) we can now use this custom token to our liking :)

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Latest posts

Featured

Last news