Add new "root or term" default token

Created on 17 January 2017, almost 8 years ago
Updated 29 September 2023, about 1 year ago

As described in this issue β†’ , it's can be confusing that the "root" token does not return anything if the relevant term is actually itself the root. I'd suggest that we add another token to the module to account for this. It would be as simple as adding a few lines to the module file. Basically all that is needed is to modify the "root" token to state that if the current term is "not !=" the root term, then use the term label as the token replacement.

Not an expert at making patches, but could figure it out again if needed. Is my logic here sound? It seems like a no-brainer to include this token in the core module's functionality.

/**
 * Implements hook_token_info().
 */
function tokens_token_info() {
    $info = array();
    $info['tokens']['term']['root-or-current'] = array(
        'name' => t('Root or Current Term'),
        'description' => t("The root term of the taxonomy term unless the term itself is the root."),
        'type' => 'term',
    );
    
    return $info;
}

/**
 * Implements hook_tokens().
 */
function tokens_tokens($type, array $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) {
    if ($type == 'term' && !empty($data['term'])) {

$term = $data['term'];

        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'root-or-current':
                    $storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
                    $parents = $storage ->loadAllParents($term->id());
                    $root_term = end($parents);
                    if ($root_term->id() != $term->id()) {
                        $replacements[$original] = $root_term->label();
                    }
                    else {
                        $replacements[$original] = $term->label();
                    }
                    break;
            }
        } 
    }
    
    return $replacements;
}
✨ Feature request
Status

Needs work

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States mrweiner

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

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States jay.dansand Appleton, WI, USA

    Thank you for this patch!

    #11 worked to solve our problem. Any reason this has stalled out for more than 2 years? There are use cases where it's a pretty critical ability - get the root item, including if the current item is the root item.

    Anyway, +1 RTBC!

Production build 0.71.5 2024