class FileVideoFormatter

Same name and namespace in other branches
  1. 10 core/modules/file/src/Plugin/Field/FieldFormatter/FileVideoFormatter.php \Drupal\file\Plugin\Field\FieldFormatter\FileVideoFormatter
  2. 11.x core/modules/file/src/Plugin/Field/FieldFormatter/FileVideoFormatter.php \Drupal\file\Plugin\Field\FieldFormatter\FileVideoFormatter
  3. 9 core/modules/file/src/Plugin/Field/FieldFormatter/FileVideoFormatter.php \Drupal\file\Plugin\Field\FieldFormatter\FileVideoFormatter
  4. 8.9.x core/modules/file/src/Plugin/Field/FieldFormatter/FileVideoFormatter.php \Drupal\file\Plugin\Field\FieldFormatter\FileVideoFormatter

Plugin implementation of the 'file_video' formatter.

Attributes

#[FieldFormatter(id: 'file_video', label: new TranslatableMarkup('Video'), description: new TranslatableMarkup('Display the file using an HTML5 video tag.'), field_types: [ 'file', ])]

Hierarchy

Expanded class hierarchy of FileVideoFormatter

2 files declare their use of FileVideoFormatter
FileVideoFormatterTest.php in core/modules/file/tests/src/Functional/Formatter/FileVideoFormatterTest.php
FileVideoPosterFormatterTest.php in core/modules/file/tests/src/Functional/Formatter/FileVideoPosterFormatterTest.php

File

core/modules/file/src/Plugin/Field/FieldFormatter/FileVideoFormatter.php, line 25

Namespace

Drupal\file\Plugin\Field\FieldFormatter
View source
class FileVideoFormatter extends FileMediaFormatterBase {
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container->get('current_user'), $container->get('entity_type.manager')
      ->getStorage('image_style'), $container->get('entity_field.manager'));
  }
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, protected AccountInterface $currentUser, protected EntityStorageInterface $imageStyleStorage, protected EntityFieldManagerInterface $entityFieldManager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
  }
  
  /**
   * {@inheritdoc}
   */
  public static function getMediaType() {
    return 'video';
  }
  
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'muted' => FALSE,
      'playsinline' => FALSE,
      'width' => 640,
      'height' => 480,
      'poster' => '',
      'poster_image_style' => '',
    ] + parent::defaultSettings();
  }
  
  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $fields = $this->entityFieldManager
      ->getFieldDefinitions($form['#entity_type'], $form['#bundle']);
    // Get all image fields for html5 poster.
    $image_fields = [];
    foreach ($fields as $field) {
      if ($field->getType() == 'image') {
        $image_fields[$field->getName()] = $field->getLabel();
      }
    }
    $image_styles = \Drupal::service(ImageDerivativeUtilities::class)->styleOptions();
    $image_styles_description_link = Link::fromTextAndUrl($this->t('Configure Image Styles'), Url::fromRoute('entity.image_style.collection'));
    return parent::settingsForm($form, $form_state) + [
      'muted' => [
        '#title' => $this->t('Muted'),
        '#type' => 'checkbox',
        '#default_value' => $this->getSetting('muted'),
      ],
      'playsinline' => [
        '#title' => $this->t('Plays Inline'),
        '#type' => 'checkbox',
        '#default_value' => $this->getSetting('playsinline'),
      ],
      'width' => [
        '#type' => 'number',
        '#title' => $this->t('Width'),
        '#default_value' => $this->getSetting('width'),
        '#size' => 5,
        '#maxlength' => 5,
        '#field_suffix' => $this->t('pixels'),
        // A width of zero pixels would make this video invisible.
'#min' => 1,
      ],
      'height' => [
        '#type' => 'number',
        '#title' => $this->t('Height'),
        '#default_value' => $this->getSetting('height'),
        '#size' => 5,
        '#maxlength' => 5,
        '#field_suffix' => $this->t('pixels'),
        // A height of zero pixels would make this video invisible.
'#min' => 1,
      ],
      'poster' => [
        '#type' => 'select',
        '#title' => $this->t('Poster field'),
        '#description' => $this->t('An image field to use as the source of the poster attribute'),
        '#default_value' => $this->getSetting('poster'),
        '#options' => $image_fields,
        '#empty_option' => $this->t('- None -'),
      ],
      'poster_image_style' => [
        '#type' => 'select',
        '#title' => $this->t('Poster field image style'),
        '#default_value' => $this->getSetting('poster_image_style'),
        '#options' => $image_styles,
        '#empty_option' => $this->t('None (original image)'),
        '#description' => $image_styles_description_link->toRenderable() + [
          '#access' => $this->currentUser
            ->hasPermission('administer image styles'),
        ],
        '#states' => [
          'visible' => [
            ':input[name$="[settings][poster]"]' => [
              'filled' => TRUE,
            ],
          ],
        ],
      ],
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();
    $summary[] = $this->t('Muted: %muted', [
      '%muted' => $this->getSetting('muted') ? $this->t('yes') : $this->t('no'),
    ]);
    $summary[] = $this->t('Plays Inline: %playsinline', [
      '%playsinline' => $this->getSetting('playsinline') ? $this->t('yes') : $this->t('no'),
    ]);
    $summary[] = $this->t('Size: %width x %height pixels', [
      '%width' => $this->getSetting('width'),
      '%height' => $this->getSetting('height'),
    ]);
    if (!empty($this->getSetting('poster'))) {
      $summary[] = $this->t('Poster field: %poster', [
        '%poster' => $this->getSetting('poster'),
      ]);
      $summary[] = $this->t('Poster image style: %poster_image_style', [
        '%poster_image_style' => $this->getSetting('poster_image_style') ?: $this->t('None (original image)'),
      ]);
    }
    if (!empty($this->getSetting('transcript'))) {
      $summary[] = $this->t('Transcript field: %transcript', [
        '%transcript' => $this->getSetting('transcript'),
      ]);
    }
    if ($width = $this->getSetting('width')) {
      $summary[] = $this->t('Width: %width pixels', [
        '%width' => $width,
      ]);
    }
    if ($height = $this->getSetting('height')) {
      $summary[] = $this->t('Height: %height pixels', [
        '%height' => $height,
      ]);
    }
    return $summary;
  }
  
  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) : array {
    $elements = parent::viewElements($items, $langcode);
    /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
    $entity = $items->getEntity();
    if (!empty($this->getSetting('poster')) && !$entity->get($this->getSetting('poster'))
      ->isEmpty()) {
      $poster_file_item = $entity->get($this->getSetting('poster'))[0];
      $poster_file_entity = $poster_file_item->entity;
      // Set the entity in the correct language for display.
      if ($poster_file_entity instanceof TranslatableInterface && $poster_file_entity->hasTranslation($langcode)) {
        $poster_file_entity = $poster_file_entity->getTranslation($langcode);
      }
      $poster_image_style_id = $this->getSetting('poster_image_style');
      if (!empty($poster_image_style_id)) {
        // With imagecache selected:
        $poster_image_style = $this->imageStyleStorage
          ->load($poster_image_style_id);
        CacheableMetadata::createFromObject($poster_image_style)->applyTo($elements);
        $poster_url = $poster_image_style->buildUrl($poster_file_entity->getFileUri());
      }
      else {
        // Without imagecache:
        $poster_url = $poster_file_entity->createFileUrl();
      }
      CacheableMetadata::createFromObject($poster_file_entity)->applyTo($elements);
      $poster_attributes = new Attribute();
      $poster_attributes->setAttribute('poster', $poster_url);
      $elements[0]['#attributes']->merge($poster_attributes);
    }
    return $elements;
  }
  
  /**
   * {@inheritdoc}
   */
  protected function prepareAttributes(array $additional_attributes = []) {
    $attributes = parent::prepareAttributes([
      'muted',
      'playsinline',
    ]);
    if ($width = $this->getSetting('width')) {
      $attributes->setAttribute('width', $width);
    }
    if ($height = $this->getSetting('height')) {
      $attributes->setAttribute('height', $height);
    }
    return $attributes;
  }
  
  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() : array {
    $dependencies = parent::calculateDependencies();
    $style_id = $this->getSetting('poster_image_style');
    /** @var \Drupal\image\ImageStyleInterface $style */
    if ($style_id && $style = ImageStyle::load($style_id)) {
      // If this formatter uses a valid image style to display the image, add
      // the image style configuration entity as dependency of this formatter.
      $dependencies[$style->getConfigDependencyKey()][] = $style->getConfigDependencyName();
    }
    return $dependencies;
  }
  
  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) : bool {
    $changed = parent::onDependencyRemoval($dependencies);
    $style_id = $this->getSetting('poster_image_style');
    /** @var \Drupal\image\ImageStyleInterface $style */
    if ($style_id && $style = ImageStyle::load($style_id)) {
      if (!empty($dependencies[$style->getConfigDependencyKey()][$style->getConfigDependencyName()])) {
        $replacement_id = $this->imageStyleStorage
          ->getReplacementId($style_id);
        // If a valid replacement has been provided in the storage, replace the
        // image style with the replacement and signal that the formatter plugin
        // settings were updated.
        if (!empty($replacement_id) && ImageStyle::load($replacement_id)) {
          $this->setSetting('poster_image_style', $replacement_id);
          $changed = TRUE;
        }
      }
    }
    return $changed;
  }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
AutowiredInstanceTrait::createInstanceAutowired public static function Instantiates a new instance of the implementing class using autowiring.
AutowiredInstanceTrait::getAutowireArguments private static function Resolves arguments for a method using autowiring.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityReferenceFormatterBase::getEntitiesToView protected function Returns the referenced entities for display. 1
EntityReferenceFormatterBase::prepareView public function Loads the entities referenced in that field across all the entities being
viewed.
Overrides FormatterBase::prepareView
EntityReferenceFormatterBase::view public function Overrides FormatterBase::view
FileFormatterBase::checkAccess protected function Checks access to the given entity. Overrides EntityReferenceFormatterBase::checkAccess 1
FileFormatterBase::needsEntityLoad protected function Returns whether the entity referenced by an item needs to be loaded. Overrides EntityReferenceFormatterBase::needsEntityLoad 1
FileMediaFormatterBase::getHtmlTag protected function Gets the HTML tag for the formatter.
FileMediaFormatterBase::getSourceFiles protected function Gets source files with attributes.
FileMediaFormatterBase::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterBase::isApplicable
FileMediaFormatterBase::mimeTypeApplies protected static function Check if given MIME type applies to the media type of the formatter.
FileVideoFormatter::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginSettingsBase::calculateDependencies
FileVideoFormatter::create public static function Instantiates a new instance of the implementing class using autowiring. Overrides FormatterBase::create
FileVideoFormatter::defaultSettings public static function Defines the default settings for this plugin. Overrides FileMediaFormatterBase::defaultSettings
FileVideoFormatter::getMediaType public static function Gets the applicable media type for a formatter. Overrides FileMediaFormatterInterface::getMediaType
FileVideoFormatter::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsBase::onDependencyRemoval
FileVideoFormatter::prepareAttributes protected function Prepare the attributes according to the settings. Overrides FileMediaFormatterBase::prepareAttributes
FileVideoFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FileMediaFormatterBase::settingsForm
FileVideoFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FileMediaFormatterBase::settingsSummary
FileVideoFormatter::viewElements public function Builds a renderable array for a field value. Overrides FileMediaFormatterBase::viewElements
FileVideoFormatter::__construct public function Constructs a FormatterBase object. Overrides FormatterBase::__construct
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
MessengerTrait::$messenger protected property The messenger. 26
MessengerTrait::messenger public function Gets the messenger. 26
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin ID.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin ID of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language. 1

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.