Create your own tokens with a hook

Created on 16 December 2023, 7 months ago
Updated 17 December 2023, 6 months ago

Motivation

I need custom tokens for the e-mail notification.

I could create these here:
recurring_events_registration.tokens.inc

Example:

  $registrant['id'] = [
    'name' => t('Registrant ID'),
    'description' => t('Get the ID of the registrant.'),
  ];

Is there a way to do this via a hook?

✨ Feature request
Status

Fixed

Version

2.0

Component

Recurring Events Registration (Submodule)

Created by

πŸ‡©πŸ‡ͺGermany trichers

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @trichers
  • πŸ‡ΊπŸ‡ΈUnited States pixiekat

    You'll want to look at hook_tokens and hook_token_info.

    Those will let you define the tokens and define the token replacements.

  • πŸ‡ΊπŸ‡ΈUnited States owenbush Denver, CO

    There is also a patch you could apply which exposes all custom entity fields as tokens. If what you want to create a token for is a registrant field itself and not something custom then take a look at

    ✨ Consistent tokens support across all entities and fields Needs work

  • πŸ‡©πŸ‡ͺGermany trichers

    @pixiekat Thank you, it worked:

    function MY_MODULE_token_info() {
    
        $registrant = []; 
    
        $registrant['id'] = [
        'name' => t('Registrant ID'),
        'description' => t('Get the ID of the registrant.'),
        ];
    
        $registrant['uuid'] = [
        'name' => t('Registrant UUID'),
        'description' => t('Get the UUID of the registrant.'),
        ];
        
        return $registrant;
    
    }
    
    function MY_MODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
    
        $replacements = [];
    
        $registrant = !empty($data['registrant']) ? $data['registrant'] : NULL;    
        
        if ($type == 'registrant' && !empty($data['registrant'])) {
            foreach ($tokens as $name => $original) {
                switch ($name) {
                    case 'id':
                    $replacements[$original] = $registrant->id->value;
                    break;    
    
                    case 'uuid':
                    $replacements[$original] = $registrant->uuid->value;
                    break;  
                }
            }
        }
        
        return $replacements;
    }
  • Status changed to Fixed 6 months ago
  • Status changed to Fixed 6 months ago
Production build 0.69.0 2024