You are here

function tooltip_taxonomy_entity_display_build_alter in Tooltip Taxonomy 8

Implement hook_entity_display_build_alter().

File

./tooltip_taxonomy.module, line 29
Tooltip Taxonomy module help and theme functions.

Code

function tooltip_taxonomy_entity_display_build_alter(&$build, $context) {
  $entity = $context['entity'];

  // Only content entity need tooltip.
  if ($entity instanceof ContentEntityBase) {
    $field_type_manager = \Drupal::service('tooltip_taxonomy.field_type_manager');
    $tooltip_manager = \Drupal::service('tooltip_taxonomy.tooltip_manager');

    // Append RDF term mappings on displayed taxonomy links.
    foreach ($build as $field_name => $field) {

      // Only add tooltip to:
      // - content field
      // - text field.
      if ($field_type_manager
        ->isContentField($field_name) && isset($field['#field_type']) && isset($field['#view_mode']) && $field_type_manager
        ->isTextField($field['#field_type'])) {
        $tags = [];
        foreach ($field as $key => $value) {
          if (is_int($key) && !empty($value)) {
            if (!isset($value['#text']) || !isset($value['#format'])) {
              continue;
            }

            // Get the tooltip markup replacement.
            $new_text = $tooltip_manager
              ->addTooltip($field['#view_mode'], $entity, $field_name, $value, $tags);
            if (!empty($new_text)) {
              $build[$field_name][$key]['#text'] = $new_text;
            }
          }
        }
        if (!empty($tags)) {
          $build[$field_name]['#cache']['tags'] = array_merge($field['#cache']['tags'], $tags);

          // Attach the CSS.
          $build[$field_name]['#attached']['library'][] = 'tooltip_taxonomy/simple_tooltip';
        }
      }
    }
  }
}