You are here

public function FileAudioFormatter::viewElements in File Entity (fieldable files) 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/FileAudioFormatter.php, line 136

Class

FileAudioFormatter
Plugin implementation of the 'file_audio' formatter.

Namespace

Drupal\file_entity\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = array();
  $multiple_file_behavior = $this
    ->getSetting('multiple_file_behavior');
  $source_files = array();

  // Because we can have the files grouped in a single audio tag, we do a
  // grouping in case the multiple file behavior is not 'tags'.
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $file) {
    if ($file
      ->getMimeTypeType() == 'audio') {
      $source_attributes = new Attribute();
      $source_attributes
        ->setAttribute('src', file_create_url($file
        ->getFileUri()));
      $source_attributes
        ->setAttribute('type', $file
        ->getMimeType());
      if ($multiple_file_behavior == 'tags') {
        $source_files[] = array(
          array(
            'file' => $file,
            'source_attributes' => $source_attributes,
          ),
        );
      }
      else {
        $source_files[0][] = array(
          'file' => $file,
          'source_attributes' => $source_attributes,
        );
      }
    }
  }
  if (!empty($source_files)) {

    // Prepare the audio attributes according to the settings.
    $audio_attributes = new Attribute();
    foreach (array(
      'controls',
      'autoplay',
      'loop',
    ) as $attribute) {
      if ($this
        ->getSetting($attribute)) {
        $audio_attributes
          ->setAttribute($attribute, $attribute);
      }
    }
    foreach ($source_files as $delta => $files) {
      $elements[$delta] = array(
        '#theme' => 'file_entity_audio',
        '#attributes' => $audio_attributes,
        '#files' => $files,
      );
      foreach ($files as $file) {
        $this->renderer
          ->addCacheableDependency($elements[$delta], $file['file']);
      }
    }
  }
  return $elements;
}