Add the tooltip on entity view too

Created on 6 June 2025, about 2 months ago

Problem/Motivation

The field's description (as in the config file) is useful to describe the field even on entity visualization (not only in the form for editors), so I wonder if it would be possible to add the tooltip besides the field label also on the formatters.

Feature request
Status

Active

Version

1.0

Component

Code

Created by

🇮🇹Italy kopeboy Milan

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

Comments & Activities

  • Issue created by @kopeboy
  • 🇮🇹Italy kopeboy Milan

    Proof of Concept: add a formatter like

    namespace Drupal\field_description_tooltip\Plugin\Field\FieldFormatter;
    
    use Drupal\Core\Field\FieldItemListInterface;
    use Drupal\Core\Field\FormatterBase;
    use Drupal\Core\Form\FormStateInterface;
    
    /**
     * Plugin implementation of the 'description_tooltip_label' formatter.
     *
     * @FieldFormatter(
     *   id = "description_tooltip_label",
     *   label = @Translation("With Description Tooltip on Label"),
     *   field_types = {
     *     "string", "text", "integer", "entity_reference", "boolean", "list_string"
     *     // Add more types or use BaseFieldDefinition if general.
     *   }
     * )
     */
    class DescriptionTooltipLabelFormatter extends FormatterBase {
    
      /**
       * {@inheritdoc}
       */
      public function viewElements(FieldItemListInterface $items, $langcode) {
      $elements = [];
    
      $description = $this->getFieldDefinition()->getDescription();
      $label = $this->getFieldDefinition()->getLabel();
    
      // Render all field values together.
      $values = [];
      foreach ($items as $item) {
        $values[] = $item->view($langcode);
      }
    
      $elements[] = [
        '#type' => 'inline_template',
        '#template' => '
          <div class="field-tooltip">
            <div class="field-label" title="{{ description }}"><strong>{{ label }}</strong>:</div>
            <div class="field-items">
              {% for value in values %}
                <div class="field-item">{{ value }}</div>
              {% endfor %}
            </div>
          </div>',
        '#context' => [
          'description' => $description,
          'label' => $label,
          'values' => $values,
        ],
      ];
    
      return $elements;
    }
    
Production build 0.71.5 2024