Newer
Older
<?php
/**
* @file
* Contains \Drupal\taxonomy\Plugin\field\formatter\LinkFormatter.
*/
Alex Pott
committed
namespace Drupal\taxonomy\Plugin\Field\FieldFormatter;
Alex Pott
committed
use Drupal\Core\Field\FieldItemListInterface;
/**
* Plugin implementation of the 'taxonomy_term_reference_link' formatter.
*
Alex Pott
committed
* @FieldFormatter(
* id = "taxonomy_term_reference_link",
* label = @Translation("Link"),
* field_types = {
* "taxonomy_term_reference"
* }
* )
*/
class LinkFormatter extends TaxonomyFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
$elements = array();
Dries Buytaert
committed
// Terms without target_id do not exist yet, theme such terms as just their
// name.
foreach ($items as $delta => $item) {
Dries Buytaert
committed
if (!$item->target_id) {
$elements[$delta] = array(
Dries Buytaert
committed
'#markup' => check_plain($item->entity->label()),
);
}
else {
Alex Pott
committed
/** @var $term \Drupal\taxonomy\TermInterface */
Dries Buytaert
committed
$term = $item->entity;
Alex Pott
committed
$uri = $term->urlInfo();
$elements[$delta] = array(
'#type' => 'link',
'#title' => $term->label(),
Alex Pott
committed
'#route_name' => $uri['route_name'],
'#route_parameters' => $uri['route_parameters'],
'#options' => $uri['options'],
);
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 should not be rendered in the field template.
unset($item->_attributes);
}
}
}
return $elements;
}
}