Newer
Older
Dries Buytaert
committed
<?php
/**
* @file
Alex Pott
committed
* Contains \Drupal\entity_reference\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter.
Dries Buytaert
committed
*/
Alex Pott
committed
namespace Drupal\entity_reference\Plugin\Field\FieldFormatter;
Dries Buytaert
committed
use Drupal\Component\Utility\String;
Alex Pott
committed
use Drupal\Core\Field\FieldItemListInterface;
Dries Buytaert
committed
/**
* Plugin implementation of the 'entity reference label' formatter.
*
Alex Pott
committed
* @FieldFormatter(
Dries Buytaert
committed
* id = "entity_reference_label",
* label = @Translation("Label"),
* description = @Translation("Display the label of the referenced entities."),
* field_types = {
* "entity_reference"
* }
* )
*/
class EntityReferenceLabelFormatter extends EntityReferenceFormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
'link' => TRUE,
) + parent::defaultSettings();
}
Dries Buytaert
committed
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function settingsForm(array $form, array &$form_state) {
$elements['link'] = array(
'#title' => t('Link label to the referenced entity'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('link'),
);
return $elements;
}
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function settingsSummary() {
$summary = array();
$summary[] = $this->getSetting('link') ? t('Link to the referenced entity') : t('No link');
Alex Pott
committed
return $summary;
Dries Buytaert
committed
}
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function viewElements(FieldItemListInterface $items) {
Dries Buytaert
committed
$elements = array();
foreach ($items as $delta => $item) {
catch
committed
if (!$item->access) {
// User doesn't have access to the referenced entity.
continue;
}
Alex Pott
committed
/** @var $referenced_entity \Drupal\Core\Entity\EntityInterface */
catch
committed
if ($referenced_entity = $item->entity) {
$label = $referenced_entity->label();
// If the link is to be displayed and the entity has a uri, display a
// link.
Alex Pott
committed
if ($this->getSetting('link') && $uri = $referenced_entity->urlInfo()) {
Dries Buytaert
committed
$elements[$delta] = array(
'#type' => 'link',
'#title' => $label,
Angie Byron
committed
) + $uri->toRenderArray();
if (!empty($item->_attributes)) {
$elements[$delta]['#options'] += array('attributes' => array());
$elements[$delta]['#options']['attributes'] += $item->_attributes;
// Unset field item attributes since they have been included in the
// formatter output and shouldn't be rendered in the field template.
unset($item->_attributes);
}
Dries Buytaert
committed
}
else {
$elements[$delta] = array('#markup' => String::checkPlain($label));
Dries Buytaert
committed
}
$elements[$delta]['#cache']['tags'] = $referenced_entity->getCacheTag();
Dries Buytaert
committed
}
}
return $elements;
}
Angie Byron
committed