You are here

entity_class_formatter.module in Entity Class Formatter 8

Entity Class Formatter module.

File

entity_class_formatter.module
View source
<?php

/**
 * @file
 * Entity Class Formatter module.
 */
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\layout_builder\Entity\LayoutEntityDisplayInterface;

/**
 * Implements hook_entity_view_alter().
 */
function entity_class_formatter_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {

  // Skip entities which are not holding fields.
  if (!$entity instanceof FieldableEntityInterface) {
    return;
  }
  $fields = [];

  // Get fields configured by Layout Builder.
  if ($display instanceof LayoutEntityDisplayInterface && $display
    ->isLayoutBuilderEnabled()) {
    foreach ($display
      ->getSections() as $section) {
      foreach ($section
        ->getComponents() as $component) {
        $config = $component
          ->get('configuration');

        // Only if Entity Class formatter is used.
        if (isset($config['id']) && isset($config['formatter']['type'])) {
          $formatter = $config['formatter'];
          if ($formatter['type'] === 'entity_class_formatter') {

            // Extract field name from the component ID.
            [
              ,
              ,
              ,
              $name,
            ] = explode(':', $config['id']);
            if (!empty($name)) {
              $fields[$name][] = !empty($formatter['settings']) ? $formatter['settings'] : [];
            }
          }
        }
      }
    }
  }
  else {
    foreach ($display
      ->getComponents() as $name => $component) {

      // Only if Entity Class formatter is used.
      if (isset($component['type']) && $component['type'] === 'entity_class_formatter') {
        $fields[$name][] = !empty($component['settings']) ? $component['settings'] : [];
      }
    }
  }

  // Process all discovered fields.
  foreach ($fields as $name => $settings_set) {
    if (!$entity
      ->hasField($name)) {
      continue;
    }
    $field = $entity
      ->get($name);

    // Apply settings of every field instance.
    foreach ($settings_set as $settings) {
      _entity_class_formatter_apply($build, $field, $settings);
    }
  }
}

/**
 * Applies all field values using defined settings.
 */
function _entity_class_formatter_apply(array &$build, FieldItemListInterface $field, array $settings) {
  $values = [];
  $field_definition = $field
    ->getFieldDefinition();

  // Get prefix to be attached before.
  $prefix = !empty($settings['prefix']) ? $settings['prefix'] : '';

  // Get suffix to be attached after.
  $suffix = !empty($settings['suffix']) ? $settings['suffix'] : '';

  // Get attribute name (class by default).
  $attr = !empty($settings['attr']) ? $settings['attr'] : 'class';

  // Only for entity reference field type.
  if ($field instanceof EntityReferenceFieldItemListInterface) {
    foreach ($field
      ->referencedEntities() as $referenced_entity) {

      // Fill title if not empty.
      $title = $referenced_entity
        ->label();
      if (!empty($title)) {
        $values[] = $prefix . $title . $suffix;
      }
    }
  }
  elseif ($field_definition
    ->getType() === 'boolean') {

    // Fill configured label based on value.
    if (filter_var($field->value, FILTER_VALIDATE_BOOLEAN)) {
      $label = $field_definition
        ->getSetting('on_label');
    }
    else {
      $label = $field_definition
        ->getSetting('off_label');
    }
    $values[] = $prefix . $label . $suffix;
  }
  else {
    foreach ($field
      ->getValue() as $item) {

      // Fill value if not empty.
      if (!empty($item['value'])) {

        // Split value into multiple classes when spaces are used.
        if ($attr === 'class') {
          foreach (explode(' ', $item['value']) as $class) {
            $values[] = $prefix . $class . $suffix;
          }
        }
        else {

          // Provide other attribute value as it is.
          $values[] = $prefix . $item['value'] . $suffix;
        }
      }
    }
  }

  // Process all discovered values.
  $method = $attr === 'class' ? 'getClass' : 'escape';
  foreach ($values as $value) {
    $build['#attributes'][$attr][] = Html::$method($value);
  }
}

Functions

Namesort descending Description
entity_class_formatter_entity_view_alter Implements hook_entity_view_alter().
_entity_class_formatter_apply Applies all field values using defined settings.