This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Secure Any CMS With Ease with Our Malware Protection Add-On! LEARN MORE→

How to Create Custom Drupal 8 Tokens Modules

Updated on May 2, 2018

3 Min Read
Create-Custom-Tokens-in-Drupal

In a previous blog post, I explained the process of creating a form using Drupal 8 Webform Module, this time we will discuss the process of creating Custom Tokens in Drupal 8.

Tokens is a fundamental element in any Drupal site. It comprises of custom pieces of text that can be used as placeholders for predefined values. These tokens are placed in a [token:type] format.

While there are many tokens available for Drupal via the API provided by the Drupal token module, there will come a time when a Drupal site builder requires the use of a custom token.

This guide not only provides valuable insights into customization but also underscores the dynamic potential of Drupal hosting in enabling tailored solutions for your website.

Create Custom Modules

In order to create a custom token, you will first need to create a custom Drupal token module which will use the two important parts for this process, declaring the token (by using hook_token_info()) and providing values for the token (by using hook_tokens()).

To create a custom module, first, go to your Drupal site’s module directory and create a new folder there with your custom module name.

In this folder, create a new file with your module’s name. Example: customtokenmodule.info.yml.

Here is the code you will be using to declare your module to Drupal:

name: My Custom Module

type: module

description: 'My Custom Drupal Token Module'

dependencies:

package: My Custom Token Module

core: 8.x

Save the file.  go to your Drupal site and enable the module.

enable custom module

Nothing as Easy as Deploying Drupal Apps on Cloud

With Cloudways, you can have your PHP apps up and running on managed cloud servers in just a few minutes.

Create Token File

Now that we have created a custom Drupal token module, we need to include token functionality in it. As mentioned earlier, we will be making use of the hook_token_info() and hook_tokens() functions.

So, create a file inside your custom module directory and give it the same name as your custom module but with the extension .tokens.inc. In my case, it will be customtokenmodule.token.inc.

In this file, implement the following code:

<?php

/**

* Implements hook_token_info().

*/

function mycustomtokenmodule_token_info() {

   $type = [

       'name' => t('Custom Token'),

       'description' => t('Tokens for custom things.'),

   ];



   $node['title'] = [

       'name' => t("Node Title"),

       'description' => t('The node\'s title'),

   ];



   $node['dateformat'] = [

       'name' => t("Custom Date Format"),

       'dynamic' => TRUE,

       'description' => t('Show a custom format for the current date'),

   ];



   return [

       'types' => ['customtoken' => $type],

       'tokens' => ['customtoken' => $node],

   ];

}



/**

* Implements hook_tokens().

*/

function mycustomtokenmodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {



   $replacements = [];

   

   if ($type == 'customtoken' && !empty($data['node'])) {

       foreach ($tokens as $name => $original) {

           switch ($name) {

               case 'title':

                   $replacements[$original] = $data['node']->getTitle();

               break;

           }

       }

       if ($dateTokens = \Drupal::token()->findWithPrefix($tokens, 'dateformat')) {

           // var_dump($dateTokens)

           // retult: array(1) { ["Y-m-d"]=> string(30) "[customtoken:dateformat:Y-m-d]" }

           foreach ($dateTokens as $format => $original) {

               $replacements[$original] = date($format);

           }

       }

   }



   return $replacements;

}

The first part of the code that uses the hook_token_info() function is used to declare the tokens as well as what function it should perform and make them visible to Drupal.

custom tokens list

In the second half of the code, the hook_tokens() function is used to actually make the token perform its desired function.

Conclusion

That’s it.

I have successfully created a custom Drupal token module.

Remember, the two most crucial aspects in this process are the utilization of the hook_token_info() and hook_tokens() functions.

I hope you found this post useful.

Let me know if you have any questions and I’ll be happy to answer them.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Claim Now