You are here

class FileDownloadLinkMedia in File Download Link 8

Plugin implementation of the 'file_download_link_media' formatter.

Plugin annotation


@FieldFormatter(
  id = "file_download_link_media",
  label = @Translation("File Download Link"),
  field_types = {
    "entity_reference",
  }
)

Hierarchy

Expanded class hierarchy of FileDownloadLinkMedia

1 file declares its use of FileDownloadLinkMedia
FileDownloadLinkMediaApplicableTest.php in tests/src/Kernel/FileDownloadLinkMediaApplicableTest.php

File

modules/file_downoad_link_media/src/Plugin/Field/FieldFormatter/FileDownloadLinkMedia.php, line 26

Namespace

Drupal\file_download_link_media\Plugin\Field\FieldFormatter
View source
class FileDownloadLinkMedia extends EntityReferenceFormatterBase implements ContainerFactoryPluginInterface {

  /**
   * Module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandler
   */
  protected $moduleHandler;

  /**
   * Token entity mapper service.
   *
   * @var \Drupal\token\TokenEntityMapper|null
   */
  protected $tokenEntityMapper;

  /**
   * Constructs a FileDownloadLink object.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   *   Module handler service.
   * @param \Drupal\token\TokenEntityMapper|null $token_entity_mapper
   *   Token entity mapper if token module is installed. Otherwise NULL.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, ModuleHandler $module_handler, $token_entity_mapper) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->moduleHandler = $module_handler;
    $this->tokenEntityMapper = $token_entity_mapper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $module_handler = $container
      ->get('module_handler');
    if ($module_handler
      ->moduleExists('token')) {
      $token_entity_mapper = $container
        ->get('token.entity_mapper');
    }
    else {
      $token_entity_mapper = NULL;
    }
    return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $module_handler, $token_entity_mapper);
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $options = parent::defaultSettings();
    $options['link_text'] = 'Download';
    $options['link_title'] = NULL;
    $options['new_tab'] = TRUE;
    $options['force_download'] = TRUE;
    $options['custom_classes'] = '';
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);
    $form['link_text'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Link Text'),
      '#default_value' => $this
        ->getSetting('link_text'),
      '#description' => $this
        ->t('This text is linked to the media source file. If left empty, the filename will be used.'),
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['default']['tokens'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          $this->tokenEntityMapper
            ->getTokenTypeForEntityType('file'),
          $this->tokenEntityMapper
            ->getTokenTypeForEntityType('media'),
        ],
      ];
      $form['token_example'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('Example Token'),
        '0' => [
          '#markup' => $this
            ->getTokenExampleMarkup(),
        ],
      ];
    }
    else {
      $form['token_warning'] = [
        '#type' => 'container',
        '#markup' => $this
          ->getTokenWarningMarkup(),
        '#attributes' => [
          'class' => [
            'messages messages--warning',
          ],
        ],
      ];
    }
    $form['new_tab'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Open file in new tab'),
      '#default_value' => $this
        ->getSetting('new_tab'),
    ];
    $form['force_download'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Force Download'),
      '#default_value' => $this
        ->getSetting('force_download'),
      '#description' => $this
        ->t('This adds the <i>download</i> attribute to the link, which works in many modern browsers.'),
    ];
    $form['link_title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Link Title'),
      '#default_value' => $this
        ->getSetting('link_title'),
      '#description' => $this
        ->t('Many browsers show the title attribute in a tooltip.'),
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['tokens_2'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          $this->tokenEntityMapper
            ->getTokenTypeForEntityType('file'),
          $this->tokenEntityMapper
            ->getTokenTypeForEntityType($this->fieldDefinition
            ->getTargetEntityTypeId()),
        ],
      ];
    }
    $form['custom_classes'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom CSS Classes'),
      '#default_value' => $this
        ->getSetting('custom_classes'),
      '#description' => $this
        ->t('Enter space-separated CSS classes to be added to the link.'),
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['tokens_3'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          $this->tokenEntityMapper
            ->getTokenTypeForEntityType('file'),
          $this->tokenEntityMapper
            ->getTokenTypeForEntityType('media'),
        ],
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $summary[] = $this
      ->t('Link Text: @link_text', [
      '@link_text' => $this
        ->getSetting('link_text'),
    ]);
    if ($this
      ->getSetting('new_tab')) {
      $summary[] = $this
        ->t('Open in new tab');
    }
    if ($this
      ->getSetting('force_download')) {
      $summary[] = $this
        ->t('Force download');
    }
    if ($this
      ->getSetting('link_title')) {
      $summary[] = $this
        ->t('Link Title: @link_title', [
        '@link_title' => $this
          ->getSetting('link_title'),
      ]);
    }
    if ($this
      ->getSetting('custom_classes')) {
      $summary[] = $this
        ->t('Classes: @classes', [
        '@classes' => $this
          ->getSetting('custom_classes'),
      ]);
    }
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($this
      ->getEntitiesToView($items, $langcode) as $delta => $media) {
      $media_source = $media
        ->getSource();
      $source_field = $media_source
        ->getSourceFieldDefinition($media->bundle->entity)
        ->getName();
      $elements[$delta] = $media->{$source_field}
        ->view([
        'type' => 'file_download_link',
        'label' => 'hidden',
        'settings' => $this
          ->getSettings(),
      ]);
      CacheableMetadata::createFromObject($media)
        ->applyTo($elements[$delta]);
    }
    return $elements;
  }

  /**
   * A helper function for the config form.
   *
   * @return string
   *   An example link text with tokens.
   */
  protected function getExampleToken() {
    return "[media:name] ([file:size])";
  }

  /**
   * A helper function for the config form.
   *
   * @return string
   *   An example of what token could do for you.
   */
  protected function getTokenWarningMarkup() {
    return $this
      ->t('<p>Enable the <a href="https://www.drupal.org/project/token" target="_blank">token module</a> to allow more flexible link text. For example, you would be able show the media name followed by the file size like this<code>@example</code></p>', [
      '@example' => $this
        ->getExampleToken(),
    ]);
  }

  /**
   * A helper function for the config form.
   *
   * @return string
   *   An example of how to leverage token.
   */
  protected function getTokenExampleMarkup() {
    return $this
      ->t('<p>You can show the media name followed by the file size like this:<code>@example</code></p>', [
      '@example' => $this
        ->getExampleToken(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {

    // This formatter is only available for entity types that reference
    // media items whose source field types are file and/or image.
    $target_type = $field_definition
      ->getFieldStorageDefinition()
      ->getSetting('target_type');
    if ($target_type != 'media') {
      return FALSE;
    }
    $media_bundles = isset($field_definition
      ->getSettings()['handler_settings']['target_bundles']) ? $field_definition
      ->getSettings()['handler_settings']['target_bundles'] : NULL;
    $media_types = MediaType::loadMultiple($media_bundles);
    foreach ($media_types as $media_type) {
      $source = $media_type
        ->getSource();
      $allowed_field_types = $source
        ->getPluginDefinition()['allowed_field_types'];
      if (!empty(array_diff($allowed_field_types, [
        'file',
        'image',
      ]))) {

        // In here means something other than file or image is allowed.
        return FALSE;
      }
    }
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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 1
DependencySerializationTrait::__wakeup public function 2
EntityReferenceFormatterBase::checkAccess protected function Checks access to the given entity. 3
EntityReferenceFormatterBase::getEntitiesToView protected function Returns the referenced entities for display. 1
EntityReferenceFormatterBase::needsEntityLoad protected function Returns whether the entity referenced by an item needs to be loaded. 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
FileDownloadLinkMedia::$moduleHandler protected property Module handler service.
FileDownloadLinkMedia::$tokenEntityMapper protected property Token entity mapper service.
FileDownloadLinkMedia::create public static function Creates an instance of the plugin. Overrides FormatterBase::create
FileDownloadLinkMedia::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
FileDownloadLinkMedia::getExampleToken protected function A helper function for the config form.
FileDownloadLinkMedia::getTokenExampleMarkup protected function A helper function for the config form.
FileDownloadLinkMedia::getTokenWarningMarkup protected function A helper function for the config form.
FileDownloadLinkMedia::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterBase::isApplicable
FileDownloadLinkMedia::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterBase::settingsForm
FileDownloadLinkMedia::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterBase::settingsSummary
FileDownloadLinkMedia::viewElements public function Builds a renderable array for a field value. Overrides FormatterInterface::viewElements
FileDownloadLinkMedia::__construct public function Constructs a FileDownloadLink 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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
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::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
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::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
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. 1
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.