EntityReferenceShsFormatter.php in Simple hierarchical select 8
File
src/Plugin/Field/FieldFormatter/EntityReferenceShsFormatter.php
View source
<?php
namespace Drupal\shs\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityInterface;
class EntityReferenceShsFormatter extends EntityReferenceLabelFormatter {
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
if (!isset($elements['link'])) {
return $elements;
}
$elements['link']['#title'] = t('Link item labels to the referenced entities');
return $elements;
}
public function settingsSummary() {
$summary = [];
$summary[] = $this
->getSetting('link') ? t('Link item labels to the referenced entities') : t('Do not create links');
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$output_as_link = $this
->getSetting('link');
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $entity) {
if ($output_as_link && !$entity
->isNew()) {
try {
$entity
->toUrl();
} catch (UndefinedLinkTemplateException $e) {
$output_as_link = FALSE;
}
}
try {
$storage = \Drupal::entityTypeManager()
->getStorage($entity
->getEntityTypeId());
$parents = $storage
->loadAllParents($entity
->id());
} catch (Exception $ex) {
$parents = [];
}
$list_items = [];
foreach (array_reverse($parents) as $entity_parent) {
if ($entity_parent
->hasTranslation($langcode)) {
$entity_parent = $entity_parent
->getTranslation($langcode);
}
if ($output_as_link) {
$uri_parent = $entity_parent
->urlInfo();
$list_items[] = [
'#type' => 'link',
'#title' => $entity_parent
->label(),
'#url' => $uri_parent,
'#options' => $uri_parent
->getOptions(),
];
}
else {
$list_items[] = [
'#plain_text' => $entity_parent
->label(),
];
}
}
$elements[$delta] = [
'#theme' => 'item_list',
'#items' => $list_items,
'#attributes' => [
'class' => [
'shs',
],
],
'#attached' => [
'library' => [
'shs/shs.formatter',
],
],
];
if (!empty($items[$delta]->_attributes)) {
if (empty($elements[$delta]['#options'])) {
$elements[$delta]['#options'] = [];
}
$elements[$delta]['#options'] += [
'attributes' => [],
];
$elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
unset($items[$delta]->_attributes);
}
if ($output_as_link) {
$elements[$delta]['#attributes']['class'][] = 'shs-linked';
}
$elements[$delta]['#cache']['tags'] = $entity
->getCacheTags();
}
return $elements;
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition
->getFieldStorageDefinition()
->getSetting('target_type') == 'taxonomy_term';
}
}