Make color available as a token

Created on 10 January 2024, 11 months ago

Problem/Motivation

Hi, I was implementing a single directory component, and wanted to pass in a color value selected in a color field. When I added the color field/entity to the path in a token, I got a fatal whitescreen error, "Expected string, got an array".

Token module's automatic expansion of fields is not getting the field value off the color entity, because it's a config entity and Token can only handle content entities.

Steps to reproduce

Here's what I did:

1. Created a custom Single Directory Component, with a "color" string property.
2. Using sdc_display module with the work done here: πŸ“Œ Implement Token Replacements Needs work , I associated my SDC with a display mode of an entity that had a color field.
3. In the Fixed Values section, I set the color field to [node:field_named_color:entity:color]

This resulted in a whitescreen error.

Proposed resolution

I'm not sure how best to implement this, but I used hook_tokens_alter to make it work, with this code:

/**
 * Implements hook_tokens_alter().
 */
function my_module_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  if (!empty($context['tokens']['entity:color'])) {
    foreach ($replacements as $key => $value) {
      if (!is_string($value) && is_a($value, '\Drupal\colorapi\Entity\Color')) {
        $replacements[$key] = $value->color;
      }
    }
  }
}

This code is working for my usage, with a color field named `field_named_color` and the token shown in step 3.

Remaining tasks

Implement an appropriate hook_tokens value to output the hex value of the color entity, and hook_token_info to make it appear in the token browser.

User interface changes

None.

API changes

Adds support for tokens.

Data model changes

None.

✨ Feature request
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States freelock Seattle

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

Comments & Activities

Production build 0.71.5 2024