Commit ddb57fd0 authored by Jan Para's avatar Jan Para

Add initial module implementation.

parent 707bcb38
# Entity Class Formatter
## Overview
Apply class on the entity if it's field is using this formatter.
## Maintainers
This module is maintained by developers at Morpht. For more information on
the company and our offerings, see [morpht.com](https://morpht.com/).
name: Entity Class Formatter
type: module
description: Apply class on the entity if it's field is using this formatter.
core: 8.x
package: Field types
dependencies:
- drupal:field
<?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;
/**
* 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;
}
// Process all fields.
foreach ($display->getComponents() as $name => $component) {
// Only if entity_class_formatter is used.
if (isset($component['type']) && $component['type'] === 'entity_class_formatter') {
// Get field object.
$field = $entity->get($name);
// Only for entity reference field type.
if ($field instanceof EntityReferenceFieldItemListInterface) {
// Process all entities referenced by current field.
foreach ($field->referencedEntities() as $entity) {
$title = $entity->label();
// Fill title as a class into the entity if is not empty.
if (!empty($title)) {
$build['#attributes']['class'][] = Html::getClass($title);
}
}
}
// Process simple fields.
else {
// Process all values of current field.
foreach ($entity->get($name)->getValue() as $value) {
// Fill value as a class into the entity if is not empty.
if (!empty($value['value'])) {
$build['#attributes']['class'][] = Html::getClass($value['value']);
}
}
}
}
}
}
<?php
namespace Drupal\entity_class_formatter\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Plugin implementation of the 'entity_class_formatter'.
*
* @FieldFormatter(
* id = "entity_class_formatter",
* label = @Translation("Entity Class"),
* field_types = {
* "string",
* "list_string",
* "entity_reference"
* }
* )
*/
class EntityClassFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
// Instead of outputting the value on the page
// we are inserting it as a class into the markup.
return [];
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment