public function DownloadLinkFormatter::viewElements in Download 8.2
Builds a renderable array for a field value.
Parameters
\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.
string $langcode: The language that should be used to render the field.
Return value
array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.
Overrides FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ DownloadLinkFormatter.php, line 21 - Contains \Drupal\download\Plugin\Field\FieldFormatter\DownloadLinkFormatter.
Class
- DownloadLinkFormatter
- Plugin annotation @FieldFormatter( id = "download_link_formatter", label = @Translation("Download link formatter"), field_types = {"download_link"} )
Namespace
Drupal\download\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$output = array();
$entity = $items
->getEntity();
foreach ($items as $delta => $item) {
$element = array();
$element['container'] = array(
'#type' => 'container',
'#attributes' => array(
'class' => array(
'download_link',
),
),
);
$valid_file_found = FALSE;
$fname = NULL;
if ($item->download_fields) {
$fields = unserialize($item->download_fields);
foreach ($fields as $fieldname) {
$files = $entity->{$fieldname};
if ($files instanceof FieldItemListInterface && !$files
->isEmpty()) {
foreach ($files as $file) {
$fileEntity = $file->entity;
$uri = $fileEntity
->getFileUri();
if (file_valid_uri($uri)) {
$valid_file_found = TRUE;
$fname = $items
->getName();
}
}
}
}
}
if ($valid_file_found) {
$element['container']['value'] = array(
'#type' => 'link',
'#title' => $item
->get('download_label')
->getValue(),
'#url' => Url::fromRoute('download.download', array(
'bundle' => $entity
->bundle(),
'entity_type' => $entity
->getEntityTypeId(),
'fieldname' => $fname,
'entity_id' => $entity
->id(),
'delta' => $delta,
)),
);
$output[$delta] = $element;
}
}
return $output;
}