ExampleMultilingualField.php in Extra Field 8.2
File
modules/extra_field_example/src/Plugin/ExtraField/Display/ExampleMultilingualField.php
View source
<?php
namespace Drupal\extra_field_example\Plugin\ExtraField\Display;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\extra_field\Plugin\ExtraFieldDisplayFormattedBase;
class ExampleMultilingualField extends ExtraFieldDisplayFormattedBase {
public function viewElements(ContentEntityInterface $entity) {
$elements = [];
$cache = new CacheableMetadata();
$tagsField = $this
->getTagsField();
if ($tagsField && !$tagsField
->isEmpty()) {
$tags = [];
foreach ($tagsField as $item) {
$tag = $item->entity;
$tags[] = $tag
->label();
$cache
->addCacheableDependency($tag);
}
$elements = [
'#markup' => implode(', ', $tags),
];
}
else {
$this->isEmpty = TRUE;
}
$cache
->applyTo($elements);
return $elements;
}
public function getLabel() {
$label = '';
if ($tagsField = $this
->getTagsField()) {
$label = $tagsField
->getFieldDefinition()
->getLabel();
}
return $label;
}
public function getLabelDisplay() {
return 'inline';
}
public function isTranslatable() {
return TRUE;
}
public function getLangcode() {
if ($tagsField = $this
->getTagsField()) {
$langcode = $tagsField
->getLangcode();
}
else {
$langcode = parent::getLangcode();
}
return $langcode;
}
protected function getTagsField() {
$field = NULL;
$entity = $this
->getEntity();
if ($entity
->hasField('field_tags')) {
$field = $entity
->get('field_tags');
}
return $field;
}
}