Browse Source

initial commit

main
astanley 11 hours ago
commit
90a0de695c
  1. 39
      README.md
  2. 6
      composer.json
  3. 1
      config/install/dynamic_field_label.settings.yml
  4. 10
      config/schema/dynamic_field_label.schema.yml
  5. 7
      dynamic_field_label.info.yml
  6. 5
      dynamic_field_label.links.menu.yml
  7. 108
      dynamic_field_label.module
  8. 3
      dynamic_field_label.permissions.yml
  9. 7
      dynamic_field_label.routing.yml
  10. 62
      src/Form/SettingsForm.php
  11. 24
      src/LabelParser.php
  12. 12
      templates/field--dynamic-field-label.html.twig
  13. 22
      tests/src/Unit/LabelParserTest.php

39
README.md

@ -0,0 +1,39 @@
# Dynamic Field Label
Drupal 10/11 custom module for existing configurable text fields. No field type,
field schema, import or stored data changes are required.
## Installation
Place this directory in `web/modules/custom/dynamic_field_label` (or the custom
module directory appropriate to your project), then run:
```sh
drush en dynamic_field_label -y
drush cr
```
Go to `/admin/config/content/dynamic-field-label` and select the fields.
`field_custom` is selected by default. The configuration matches machine names
across all entity types and bundles. The permission is `administer dynamic field labels`.
## Rendering
`Publisher:University of Prince Edward Island` displays as a Publisher label
and University of Prince Edward Island value. Only the first colon is a separator.
Whitespace around both parts is trimmed. An empty value is permitted; an empty
label or missing colon falls back to the existing formatter output. Multiple
values each receive their own label. Embedded labels are shown even if the
Drupal label is hidden. Labels are escaped plain text and must not contain HTML tags. Values from
formatted text fields are rendered through Drupal’s processed_text render element
using the stored text format; plain string fields and entries without a format
remain escaped plain text. Use input such as `Publisher:<strong>UPEI</strong>`.
Do not wrap the label or entire input in HTML (for example `<p>Publisher:UPEI</p>`);
such input falls back to the original formatter. Parsed entries display the full
value rather than a trimmed formatter or summary. Invalid entries preserve
formatter output; in a mixed field the original label is repeated for invalid
entries unless hidden. The module provides a field template using standard field
CSS classes; a theme can override `field--dynamic-field-label.html.twig`.

6
composer.json

@ -0,0 +1,6 @@
{
"name": "drupal/dynamic_field_label",
"description": "Display labels embedded in existing Drupal text field values.",
"type": "drupal-module",
"require": {"drupal/core": "^10 || ^11"}
}

1
config/install/dynamic_field_label.settings.yml

@ -0,0 +1 @@
fields: []

10
config/schema/dynamic_field_label.schema.yml

@ -0,0 +1,10 @@
dynamic_field_label.settings:
type: config_object
label: 'Dynamic field label settings'
mapping:
fields:
type: sequence
label: 'Selected field machine names'
sequence:
type: string
label: 'Field machine name'

7
dynamic_field_label.info.yml

@ -0,0 +1,7 @@
name: Dynamic Field Label
type: module
description: 'Display selected existing text fields using labels embedded in their values.'
package: Custom
core_version_requirement: ^10 || ^11
dependencies:
- drupal:filter

5
dynamic_field_label.links.menu.yml

@ -0,0 +1,5 @@
dynamic_field_label.settings:
title: 'Dynamic field labels'
description: 'Select text fields with embedded labels.'
route_name: dynamic_field_label.settings
parent: system.admin_config_content

108
dynamic_field_label.module

@ -0,0 +1,108 @@
<?php
/**
* @file
* Presentation-only dynamic labels for existing text fields.
*/
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\dynamic_field_label\LabelParser;
/**
* Implements hook_entity_view_alter().
*/
function dynamic_field_label_entity_view_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display): void {
// Attach even when no fields are selected, so enabling a field invalidates
// previously cached entity output. Preserve all existing cache metadata.
CacheableMetadata::createFromRenderArray($build)
->addCacheableDependency(\Drupal::config('dynamic_field_label.settings'))
->applyTo($build);
}
/**
* Implements hook_preprocess_field().
*/
function dynamic_field_label_preprocess_field(array &$variables): void {
$element = $variables['element'];
$config = \Drupal::config('dynamic_field_label.settings');
if (!in_array($element['#field_name'] ?? '', $config->get('fields') ?? [], TRUE)) {
return;
}
$items = $element['#items'] ?? NULL;
if (!$items || !in_array($items->getFieldDefinition()->getType(), ['string', 'string_long', 'text', 'text_long', 'text_with_summary'], TRUE)) {
return;
}
// Only change items actually exposed by the formatter. Preserve fallback
// content and item attributes for invalid values.
$parsed = [];
foreach ($variables['items'] as $delta => $item) {
$raw = $items->get($delta)?->value;
if (is_string($raw) && ($parts = LabelParser::parse($raw)) !== NULL) {
$parsed[$delta] = $parts;
}
}
if (!$parsed) {
return;
}
$variables['dynamic_field_label_items'] = [];
foreach ($variables['items'] as $delta => $item) {
if (isset($parsed[$delta])) {
$cacheability = CacheableMetadata::createFromRenderArray($item['content']);
$cacheability->addCacheableDependency($config);
$field_item = $items->get($delta);
$type = $items->getFieldDefinition()->getType();
// Let Drupal apply the stored text format, including its cacheability.
// Never interpret markup in an unformatted string field.
if (in_array($type, ['text', 'text_long', 'text_with_summary'], TRUE) && !empty($field_item->format)) {
$item['content'] = [
'#type' => 'processed_text',
'#text' => $parsed[$delta]['value'],
'#format' => $field_item->format,
'#langcode' => $items->getLangcode(),
];
}
else {
$item['content'] = ['#plain_text' => $parsed[$delta]['value']];
}
$cacheability->applyTo($item['content']);
$item['dynamic_label'] = $parsed[$delta]['label'];
}
else {
$item['dynamic_label'] = $variables['label_hidden'] ? NULL : $variables['label'];
}
$variables['dynamic_field_label_items'][] = $item;
}
}
/**
* Implements hook_theme().
*/
function dynamic_field_label_theme(): array {
return [
'field__dynamic_field_label' => [
'base hook' => 'field',
'template' => 'field--dynamic-field-label',
],
];
}
/**
* Implements hook_theme_suggestions_field_alter().
*/
function dynamic_field_label_theme_suggestions_field_alter(array &$suggestions, array $variables): void {
$element = $variables['element'];
$items = $element['#items'] ?? NULL;
if (!$items || !in_array($element['#field_name'] ?? '', \Drupal::config('dynamic_field_label.settings')->get('fields') ?? [], TRUE)) {
return;
}
if (!in_array($items->getFieldDefinition()->getType(), ['string', 'string_long', 'text', 'text_long', 'text_with_summary'], TRUE)) {
return;
}
foreach ($items as $item) {
if (is_string($item->value) && LabelParser::parse($item->value) !== NULL) {
$suggestions[] = 'field__dynamic_field_label';
return;
}
}
}

3
dynamic_field_label.permissions.yml

@ -0,0 +1,3 @@
administer dynamic field labels:
title: 'Administer dynamic field labels'
restrict access: true

7
dynamic_field_label.routing.yml

@ -0,0 +1,7 @@
dynamic_field_label.settings:
path: '/admin/config/content/dynamic-field-label'
defaults:
_form: '\Drupal\dynamic_field_label\Form\SettingsForm'
_title: 'Dynamic field labels'
requirements:
_permission: 'administer dynamic field labels'

62
src/Form/SettingsForm.php

@ -0,0 +1,62 @@
<?php
namespace Drupal\dynamic_field_label\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Render\Element\Checkboxes;
/**
* Selects existing configurable text fields by machine name.
*/
final class SettingsForm extends ConfigFormBase {
public function getFormId(): string {
return 'dynamic_field_label_settings';
}
protected function getEditableConfigNames(): array {
return ['dynamic_field_label.settings'];
}
public function buildForm(array $form, FormStateInterface $form_state): array {
$selected = $this->config('dynamic_field_label.settings')->get('fields') ?? [];
$options = [];
$locations = [];
foreach (FieldConfig::loadMultiple() as $field) {
if (!in_array($field->getType(), ['string', 'string_long', 'text', 'text_long', 'text_with_summary'], TRUE)) {
continue;
}
$name = $field->getName();
$locations[$name][] = $field->getLabel() . ' (' . $field->getTargetEntityTypeId() . ':' . $field->getTargetBundle() . ')';
}
foreach ($locations as $name => $labels) {
$options[$name] = $name . ' — ' . implode('; ', array_unique($labels));
}
// Preserve configured names when a field has temporarily been removed.
foreach ($selected as $name) {
$options[$name] ??= $name . ' (' . $this->t('not currently available') . ')';
}
ksort($options);
$form['fields'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Text fields'),
'#options' => $options,
'#default_value' => $selected,
'#description' => $this->t('Selected machine names apply across entity types and bundles. Values must use label:value. Labels are plain text; values retain their assigned text format for formatted fields.'),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state): void {
$fields = array_values(
Checkboxes::getCheckedCheckboxes(
$form_state->getValue('fields') ?? []
)
);
$this->config('dynamic_field_label.settings')->set('fields', $fields)->save();
parent::submitForm($form, $form_state);
}
}

24
src/LabelParser.php

@ -0,0 +1,24 @@
<?php
namespace Drupal\dynamic_field_label;
/**
* Parses plain-text labels without changing stored field values.
*/
final class LabelParser {
/**
* Splits at the first colon, returning NULL for malformed input.
*/
public static function parse(string $raw): ?array {
if (!str_contains($raw, ':')) {
return NULL;
}
[$label, $value] = array_map('trim', explode(':', $raw, 2));
// A label must be plain text. Reject markup before the separator,
// including colons occurring in HTML attributes rather than in a label.
return $label === '' || strpbrk($label, '<>') !== FALSE
? NULL : ['label' => $label, 'value' => $value];
}
}

12
templates/field--dynamic-field-label.html.twig

@ -0,0 +1,12 @@
{# Render one label per value, keeping normal field/item attributes. #}
{% set classes = ['field', 'field--name-' ~ field_name|clean_class, 'field--type-' ~ field_type|clean_class, 'field--label-' ~ label_display|clean_class] %}
<div{{ attributes.addClass(classes) }}>
{% for item in dynamic_field_label_items|default(items) %}
<div{{ item.attributes.addClass('field__item') }}>
{% if item.dynamic_label is defined and item.dynamic_label is not null %}
<div class="field__label">{{ item.dynamic_label }}</div>
{% endif %}
<div class="field__value">{{ item.content }}</div>
</div>
{% endfor %}
</div>

22
tests/src/Unit/LabelParserTest.php

@ -0,0 +1,22 @@
<?php
namespace Drupal\Tests\dynamic_field_label\Unit;
use Drupal\dynamic_field_label\LabelParser;
use Drupal\Tests\UnitTestCase;
/**
* @group dynamic_field_label
*/
final class LabelParserTest extends UnitTestCase {
public function testParsing(): void {
$this->assertSame(['label' => 'Identifier', 'value' => 'pei:123'], LabelParser::parse(' Identifier : pei:123 '));
$this->assertSame(['label' => 'Label', 'value' => ''], LabelParser::parse('Label:'));
$this->assertNull(LabelParser::parse('no separator'));
$this->assertNull(LabelParser::parse(' :value'));
$this->assertSame(['label' => 'Publisher', 'value' => '<a href="https://example.org">Example</a>'], LabelParser::parse('Publisher:<a href="https://example.org">Example</a>'));
$this->assertNull(LabelParser::parse('<p>Publisher:Example</p>'));
}
}
Loading…
Cancel
Save