You are here

class FileUrlWidget in File URL 2.0.x

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldWidget/FileUrlWidget.php \Drupal\file_url\Plugin\Field\FieldWidget\FileUrlWidget

Plugin implementation of the 'file_url_generic' widget.

Plugin annotation


@FieldWidget(
  id = "file_url_generic",
  label = @Translation("File URL"),
  field_types = {
    "file_url"
  }
)

Hierarchy

Expanded class hierarchy of FileUrlWidget

File

src/Plugin/Field/FieldWidget/FileUrlWidget.php, line 27

Namespace

Drupal\file_url\Plugin\Field\FieldWidget
View source
class FileUrlWidget extends FileWidget {

  /**
   * File URL item type: file upload.
   */
  const TYPE_UPLOAD = 'upload';

  /**
   * File URL item type: URL to remote file..
   */
  const TYPE_REMOTE = 'remote';

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'add_new_label' => 'Upload a new file or enter a URL',
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);

    // Allow configuring only if the field has multiple values.
    if ($this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getCardinality() !== 1) {
      $element['add_new_label'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Label for new item form'),
        '#default_value' => $this
          ->getSetting('add_new_label'),
      ];
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
    $elements = parent::formMultipleElements($items, $form, $form_state);

    // Use the configurable 'new item' label.
    $elements['#file_upload_title'] = $this
      ->getSetting('add_new_label');

    // The upload instructions are added directly to 'file_url' element.
    unset($elements['#file_upload_description']);
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);
    if ($this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getCardinality() === 1) {

      // On single fields show only the field description. Upload instructions
      // were moved to 'file_url' element.
      $element['#description'] = $this
        ->getFilteredDescription();
    }

    // Add our own validator.
    $element['#element_validate'] = [
      [
        static::class,
        'validate',
      ],
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function process($element, FormStateInterface $form_state, $form) {
    $file_url_type = isset($element['#value']['file_url_type']) ? $element['#value']['file_url_type'] : NULL;
    $file_url_remote = $element['#value']['file_url_remote'];
    $file_url_remote_is_valid = UrlHelper::isValid($file_url_remote, TRUE);
    if ($file_url_remote_is_valid && $file_url_type) {

      // The parent widget only populates '#files' with managed files, we add
      // the remote files too, to get them listed as items in the widget.
      $remote_file = RemoteFile::load($file_url_remote);
      $element['#files'] = [
        $file_url_remote => $remote_file,
      ];
      $file_link = [
        '#type' => 'link',
        '#title' => $remote_file
          ->getFileUri(),
        '#url' => Url::fromUri($remote_file
          ->getFileUri()),
      ];
      if ($element['#multiple']) {
        $element["file_{$file_url_remote}"]['selected'] = [
          '#type' => 'checkbox',
          '#title' => \Drupal::service('renderer')
            ->renderPlain($file_link),
        ];
      }
      else {
        $element["file_{$file_url_remote}"]['filename'] = $file_link + [
          '#weight' => -10,
        ];
      }
    }
    $access_file_url_elements = empty($element['#files']) && !$file_url_remote_is_valid || !$file_url_type;

    // Build the file URL additional sub-elements.
    $element['file_url_type'] = [
      '#type' => 'radios',
      '#options' => [
        static::TYPE_UPLOAD => t('Upload file'),
        static::TYPE_REMOTE => t('Remote file URL'),
      ],
      '#default_value' => $file_url_type,
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '</div>',
      '#access' => $access_file_url_elements,
      '#weight' => 5,
    ];
    $field_name = $element['#field_name'];
    $delta = $element['#delta'];
    $selector = ':input[name="' . $field_name . '[' . $delta . '][file_url_type]"]';
    $remote_visible = [
      $selector => [
        'value' => static::TYPE_REMOTE,
      ],
    ];
    $element['file_url_remote'] = [
      '#type' => 'url',
      '#title' => t('Remote URL'),
      '#title_display' => 'invisible',
      '#description' => t('This must be an external URL such as <em>http://example.com</em>.'),
      '#default_value' => $file_url_remote,
      // Only show this field when the 'remote' radio is selected.
      '#states' => [
        'visible' => $remote_visible,
      ],
      '#attached' => [
        // Load the JS functionality that triggers automatically the 'Upload'
        // button when a remote URL is entered.
        'library' => [
          'file_url/remote_url',
        ],
      ],
      '#attributes' => [
        // Used by 'file_url/remote_url' library identify the text field.
        'data-drupal-file-url-remote' => TRUE,
      ],
      '#access' => $access_file_url_elements,
      '#weight' => 15,
    ];

    // Only show this field when the 'upload' radio is selected. Add also a
    // wrapper around file upload, so states knows what field to target.
    $upload_visible = [
      $selector => [
        'value' => static::TYPE_UPLOAD,
      ],
    ];
    $element['upload']['#states']['visible'] = $upload_visible;
    $element['upload']['#theme_wrappers'][] = 'form_element';

    // The upload instructions are added directly to the file upload element.
    $element['upload']['#description'] = [
      '#theme' => 'file_upload_help',
      '#description' => '',
      '#upload_validators' => $element['#upload_validators'],
      '#cardinality' => $element['#cardinality'],
    ];
    $element['upload']['#weight'] = 10;

    // Make sure the upload button is the last in form element.
    $element['upload_button']['#weight'] = 20;
    return parent::process($element, $form_state, $form);
  }

  /**
   * Replaces the ManagedFile validator.
   *
   * @param array $element
   *   The element render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   * @param array $complete_form
   *   The full form render array.
   */
  public static function validate(&$element, FormStateInterface $form_state, &$complete_form) {
    $file_url_type = NestedArray::getValue($form_state
      ->getValues(), array_merge($element['#parents'], [
      'file_url_type',
    ]));
    $remote_url = NestedArray::getValue($form_state
      ->getValues(), array_merge($element['#parents'], [
      'file_url_remote',
    ]));
    $fids = NestedArray::getValue($form_state
      ->getValues(), array_merge($element['#parents'], [
      'fids',
    ]));
    if (($remote_url || $fids) && !in_array($file_url_type, [
      static::TYPE_UPLOAD,
      static::TYPE_REMOTE,
    ], TRUE)) {

      // @todo Find a way to guess the type from values. Temporary disable this
      //   validation.
      // $form_state->setError($element, t("A type should be selected. Either 'Upload file' or 'Remote file URL'."));
    }
    if ($file_url_type === static::TYPE_UPLOAD) {

      // If it's a file upload, pass it to the 'managed_file' validation.
      ManagedFile::validateManagedFile($element, $form_state, $complete_form);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function value($element, $input, FormStateInterface $form_state) {
    $file_url_remote = $file_url_type = NULL;
    if (!empty($element['#default_value']['fids'])) {
      $url = $element['#default_value']['fids'][0];
      $file = FileUrlHandler::urlToFile($url);
      if (!FileUrlHandler::isRemote($file)) {

        // Normalise managed file IDs from URLs to numeric IDs before calling
        // the parent method.
        $element['#default_value']['fids'] = [
          $file
            ->id(),
        ];
        $file_url_type = 'upload';
      }
      else {
        $file_url_remote = $url;
        $file_url_type = 'remote';
      }
    }
    $return = parent::value($element, $input, $form_state);
    if ($input !== FALSE) {
      if (isset($input['file_url_type']) && $input['file_url_type'] === static::TYPE_REMOTE) {
        if (!empty($input['file_url_remote']) && !$input['fids']) {
          $file_url_remote = $input['file_url_remote'];
        }
      }
    }
    if (!empty($file_url_remote)) {

      // The parent widget is doing this but only for managed files.
      $return['fids'] = [
        $file_url_remote,
      ];
    }

    // Provide file URL parameters as part of the value.
    if (empty($return['file_url_remote'])) {
      $return['file_url_remote'] = $file_url_remote;
    }
    if (empty($return['file_url_type'])) {
      $return['file_url_type'] = $file_url_type;
    }
    return $return;
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    $values = parent::massageFormValues($values, $form, $form_state);

    // Convert file IDs to URLs.
    foreach ($values as &$value) {
      if ($value['file_url_type'] === static::TYPE_UPLOAD) {

        /** @var \Drupal\file\FileInterface $file */
        $file = File::load((int) $value['target_id']);
        $value['target_id'] = FileUrlHandler::fileToUrl($file);
      }

      // Remove file URL specific keys from value.
      unset($value['file_url_type']);
      unset($value['file_url_remote']);
    }
    return $values;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FileUrlWidget::defaultSettings public static function Defines the default settings for this plugin. Overrides FileWidget::defaultSettings
FileUrlWidget::formElement public function Returns the form for a single field widget. Overrides FileWidget::formElement
FileUrlWidget::formMultipleElements public function Overrides \Drupal\Core\Field\WidgetBase::formMultipleElements(). Overrides FileWidget::formMultipleElements
FileUrlWidget::massageFormValues public function Massages the form values into the format expected for field values. Overrides FileWidget::massageFormValues
FileUrlWidget::process public static function Form API callback: Processes a file_generic field element. Overrides FileWidget::process
FileUrlWidget::settingsForm public function Returns a form to configure settings for the widget. Overrides FileWidget::settingsForm
FileUrlWidget::TYPE_REMOTE constant File URL item type: URL to remote file..
FileUrlWidget::TYPE_UPLOAD constant File URL item type: file upload.
FileUrlWidget::validate public static function Replaces the ManagedFile validator.
FileUrlWidget::value public static function Form API callback. Retrieves the value for the file_generic field element. Overrides FileWidget::value
FileWidget::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
FileWidget::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBase::extractFormValues
FileWidget::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBase::flagErrors
FileWidget::getDescriptionFromElement protected static function Retrieves the file description from a field field element.
FileWidget::processMultiple public static function Form API callback: Processes a group of file_generic field elements.
FileWidget::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetBase::settingsSummary 1
FileWidget::submit public static function Form submission handler for upload/remove button of formElement().
FileWidget::validateMultipleCount public static function Form element validation callback for upload element on file widget. Checks if user has uploaded more files than allowed.
FileWidget::__construct public function Constructs a WidgetBase object. Overrides WidgetBase::__construct 1
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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
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. 4
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.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface::errorElement 8
WidgetBase::form public function Creates a form element for a field. Overrides WidgetBaseInterface::form 3
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetInterface::isApplicable 4
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState