Browse Source

Initial commit

main
astanley 10 hours ago
parent
commit
03f94c61be
  1. 8
      README.md
  2. 2
      composer.json
  3. 130
      dynamic_field_label.module

8
README.md

@ -14,8 +14,8 @@ 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`.
The configuration matches machine names across all entity types and bundles.
The permission is `administer dynamic field labels`.
## Rendering
@ -30,9 +30,7 @@ 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
value rather than a trimmed formatter or summary. The module provides a field template using standard field
CSS classes; a theme can override `field--dynamic-field-label.html.twig`.

2
composer.json

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

130
dynamic_field_label.module

@ -6,17 +6,42 @@
*/
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Render\Element;
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);
function dynamic_field_label_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display): void {
// Register the dependency before rendering, even when no fields are selected.
// Selecting or deselecting fields must invalidate cached entity output.
\Drupal::service('renderer')->addCacheableDependency(
$build,
\Drupal::config('dynamic_field_label.settings'),
);
}
/**
* 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 {
if (_dynamic_field_label_parse_items($variables['element'])) {
$suggestions[] = 'field__dynamic_field_label';
}
}
/**
@ -24,35 +49,35 @@ function dynamic_field_label_entity_view_alter(array &$build, \Drupal\Core\Entit
*/
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)) {
$type = _dynamic_field_label_text_type($element);
if ($type === NULL) {
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;
}
$config = \Drupal::config('dynamic_field_label.settings');
$renderer = \Drupal::service('renderer');
// Also cover fields rendered independently of an entity view, including
// currently unselected fields and fields with malformed input.
foreach ($variables['items'] as &$item) {
$renderer->addCacheableDependency($item['content'], $config);
}
unset($item);
$parsed = _dynamic_field_label_parse_items($element);
if (!$parsed) {
return;
}
$items = $element['#items'];
$variables['dynamic_field_label_items'] = [];
foreach ($variables['items'] as $delta => $item) {
if (isset($parsed[$delta])) {
// Save metadata before replacing the original formatter render array.
$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.
// Respect the stored text format. Plain text must never become HTML.
if (in_array($type, ['text', 'text_long', 'text_with_summary'], TRUE) && !empty($field_item->format)) {
$item['content'] = [
'#type' => 'processed_text',
@ -64,45 +89,58 @@ function dynamic_field_label_preprocess_field(array &$variables): void {
else {
$item['content'] = ['#plain_text' => $parsed[$delta]['value']];
}
// Restore original metadata, including the configuration dependency.
// The processed_text element adds its own filter dependencies on render.
$cacheability->applyTo($item['content']);
$item['dynamic_label'] = $parsed[$delta]['label'];
}
else {
// Preserve the original formatter output and label for invalid input.
$item['dynamic_label'] = $variables['label_hidden'] ? NULL : $variables['label'];
}
$variables['dynamic_field_label_items'][] = $item;
$variables['dynamic_field_label_items'][$delta] = $item;
}
}
/**
* Implements hook_theme().
* Returns the field type if it is supported, or NULL otherwise.
*/
function dynamic_field_label_theme(): array {
return [
'field__dynamic_field_label' => [
'base hook' => 'field',
'template' => 'field--dynamic-field-label',
],
];
function _dynamic_field_label_text_type(array $element): ?string {
$items = $element['#items'] ?? NULL;
if ($items === NULL) {
return NULL;
}
$type = $items->getFieldDefinition()->getType();
return in_array($type, ['string', 'string_long', 'text', 'text_long', 'text_with_summary'], TRUE) ? $type : NULL;
}
/**
* Implements hook_theme_suggestions_field_alter().
* Returns parsed values keyed by the deltas exposed by the field formatter.
*
* Both theme suggestion and preprocessing use this method so a hidden or
* omitted value cannot independently trigger the dynamic field template.
*/
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;
function _dynamic_field_label_parse_items(array $element): array {
if (_dynamic_field_label_text_type($element) === NULL) {
return [];
}
if (!in_array($items->getFieldDefinition()->getType(), ['string', 'string_long', 'text', 'text_long', 'text_with_summary'], TRUE)) {
return;
$fields = \Drupal::config('dynamic_field_label.settings')->get('fields') ?? [];
if (!in_array($element['#field_name'] ?? '', $fields, TRUE)) {
return [];
}
foreach ($items as $item) {
if (is_string($item->value) && LabelParser::parse($item->value) !== NULL) {
$suggestions[] = 'field__dynamic_field_label';
return;
$parsed = [];
foreach (Element::children($element) as $delta) {
if (!is_int($delta) && !ctype_digit((string) $delta)) {
continue;
}
$raw = $element['#items']->get((int) $delta)?->value;
if (is_string($raw) && ($parts = LabelParser::parse($raw)) !== NULL) {
$parsed[$delta] = $parts;
}
}
return $parsed;
}

Loading…
Cancel
Save