Score:0

Token service not replacing text with term as a token

rs flag

I'm trying to use the token service to replace a piece of text using a Taxonomy Term.

Example:
Hi [term:field_first_name], ...

The term is getting loaded correctly, but the text is not changing:

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

    $token_service = \Drupal::token();
    $text = $token_service->replace($text, [
        'term' => $term,
    ]);

    print_r($text);

The print returns:
Hi [term:field_first_name], ...
instead of:
Hi John, ...

I'm currently using drupal version 9.3.2.

apaderno avatar
us flag
Welcome to Drupal Answers! Are you sure *field_first_name* is a field added to taxonomy terms? It seems more a user field, by its name.
rs flag
@apaderno Thank you for your answer, but it is a field, I just wanted to simplify the example.
Score:0
cn flag

Drupal out-of-the-box has only basic token support, which can replace core entity standard fields like [term:name] or [term:description].

Configured fields, usually those with a prefix field_, need the module Token to be installed. Then [term:field_first_name] will be replaced, if the field exists.

rs flag
Thank you for your answer. I know i didn't mention this, but i didn't want to rely on modules, thought it was already built in. I chose another path, looped through term: ```foreach($term as $field_name => $_)``` and then just used str_replace, to replace the text with the field names
4uk4 avatar
cn flag
I agree Drupal site owners should not install large amounts of modules, including beta or dev versions. But there are a few standard modules you can and should use if you need the functionality. And modules like Token can be installed and uninstalled with very low risk because they don't change the database schema.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.