Provide type => address token (at the Element level)

Created on 15 December 2023, 7 months ago

Problem/Motivation

We're using an "Address" Form Element, not a field (as it's a config entity):

    $form['address'] = [
      '#type' => 'address',
      '#title' => $this->t('Address'),
      '#required' => TRUE,
      '#default_value' => $this->config('my.settings')->get('address'),
    ];

this works great!

Now we wanted to provide the tokens from this field as tree. For other token types like "User" or "Date" this works well like this:

  $tokens['timestamp'] = [
    'name' => t('Timestamp'),
    'type' => 'date',
    'description' => t('The date and time of the message.'),
  ];
  $tokens['user'] = [
    'name' => t('User'),
    'type' => 'user',
    'description' => t('The user who triggered the message.'),
  ];

    if ($date_tokens = $token_service->findWithPrefix($tokens, 'timestamp')) {
      $replacements += $token_service->generate('date', $date_tokens, ['date' => $data['watchdog_mailer']['timestamp']], $options, $bubbleable_metadata);
    }
    // Load user:
    $user = !empty($data['watchdog_mailer']['uid']) ? User::load($data['watchdog_mailer']['uid']) : User::load(0);
    if (($user_tokens = $token_service->findWithPrefix($tokens, 'user'))) {
      $replacements += $token_service->generate('user', $user_tokens, ['user' => $user], $options, $bubbleable_metadata);
    }

(from https://git.drupalcode.org/project/watchdog_mailer/-/blob/2.0.x/watchdog...).

But for "type" => "address" this doesn't seem possible due to the field-specific implementation in https://git.drupalcode.org/project/address/-/blob/8.x-1.x/address.tokens...

This is what we tried:

    if ($address_tokens = $token_service->findWithPrefix($tokens, 'address')) {
      $replacements += $token_service->generate('address', $address_tokens, ['address' => $data['project']['address']], $options, $bubbleable_metadata);
    }

Steps to reproduce

Proposed resolution

Implement the token tree functionality based on the address form element, not based on the address field, so it can be used with both.

If we're just trying to use it the wrong way, we should add an example into the README.md and .api.php

Remaining tasks

User interface changes

None

API changes

Data model changes

None

✨ Feature request
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡©πŸ‡ͺGermany LRWebks Porta Westfalica

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

Comments & Activities

Production build 0.69.0 2024