class FileUrlWidget in File URL 2.0.x
Same name and namespace in other branches
- 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
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Field\WidgetBase implements WidgetInterface, ContainerFactoryPluginInterface
- class \Drupal\file\Plugin\Field\FieldWidget\FileWidget
- class \Drupal\file_url\Plugin\Field\FieldWidget\FileUrlWidget
- class \Drupal\file\Plugin\Field\FieldWidget\FileWidget
- class \Drupal\Core\Field\WidgetBase implements WidgetInterface, ContainerFactoryPluginInterface
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
Expanded class hierarchy of FileUrlWidget
File
- src/
Plugin/ Field/ FieldWidget/ FileUrlWidget.php, line 27
Namespace
Drupal\file_url\Plugin\Field\FieldWidgetView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
FileUrlWidget:: |
public static | function |
Defines the default settings for this plugin. Overrides FileWidget:: |
|
FileUrlWidget:: |
public | function |
Returns the form for a single field widget. Overrides FileWidget:: |
|
FileUrlWidget:: |
public | function |
Overrides \Drupal\Core\Field\WidgetBase::formMultipleElements(). Overrides FileWidget:: |
|
FileUrlWidget:: |
public | function |
Massages the form values into the format expected for field values. Overrides FileWidget:: |
|
FileUrlWidget:: |
public static | function |
Form API callback: Processes a file_generic field element. Overrides FileWidget:: |
|
FileUrlWidget:: |
public | function |
Returns a form to configure settings for the widget. Overrides FileWidget:: |
|
FileUrlWidget:: |
constant | File URL item type: URL to remote file.. | ||
FileUrlWidget:: |
constant | File URL item type: file upload. | ||
FileUrlWidget:: |
public static | function | Replaces the ManagedFile validator. | |
FileUrlWidget:: |
public static | function |
Form API callback. Retrieves the value for the file_generic field element. Overrides FileWidget:: |
|
FileWidget:: |
public static | function |
Creates an instance of the plugin. Overrides WidgetBase:: |
|
FileWidget:: |
public | function |
Extracts field values from submitted form values. Overrides WidgetBase:: |
|
FileWidget:: |
public | function |
Reports field-level validation errors against actual form elements. Overrides WidgetBase:: |
|
FileWidget:: |
protected static | function | Retrieves the file description from a field field element. | |
FileWidget:: |
public static | function | Form API callback: Processes a group of file_generic field elements. | |
FileWidget:: |
public | function |
Returns a short summary for the current widget settings. Overrides WidgetBase:: |
1 |
FileWidget:: |
public static | function | Form submission handler for upload/remove button of formElement(). | |
FileWidget:: |
public static | function | Form element validation callback for upload element on file widget. Checks if user has uploaded more files than allowed. | |
FileWidget:: |
public | function |
Constructs a WidgetBase object. Overrides WidgetBase:: |
1 |
MessengerTrait:: |
protected | property | The messenger. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
2 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
PluginSettingsBase:: |
protected | property | Whether default settings have been merged into the current $settings. | |
PluginSettingsBase:: |
protected | property | The plugin settings injected by third party modules. | |
PluginSettingsBase:: |
public | function |
Calculates dependencies for the configured plugin. Overrides DependentPluginInterface:: |
6 |
PluginSettingsBase:: |
public | function |
Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
protected | function | Merges default settings values into $settings. | |
PluginSettingsBase:: |
public | function |
Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface:: |
3 |
PluginSettingsBase:: |
public | function |
Sets the value of a setting for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the settings for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Unsets a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
WidgetBase:: |
protected | property | The field definition. | |
WidgetBase:: |
protected | property |
The widget settings. Overrides PluginSettingsBase:: |
|
WidgetBase:: |
public static | function | Ajax callback for the "Add another item" button. | |
WidgetBase:: |
public static | function | Submission handler for the "Add another item" button. | |
WidgetBase:: |
public static | function | After-build handler for field elements in a form. | |
WidgetBase:: |
public | function |
Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface:: |
8 |
WidgetBase:: |
public | function |
Creates a form element for a field. Overrides WidgetBaseInterface:: |
3 |
WidgetBase:: |
protected | function | Generates the form element for a single copy of the widget. | |
WidgetBase:: |
protected | function | Returns the value of a field setting. | |
WidgetBase:: |
protected | function | Returns the array of field settings. | |
WidgetBase:: |
protected | function | Returns the filtered field description. | |
WidgetBase:: |
public static | function |
Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface:: |
|
WidgetBase:: |
protected static | function | Returns the location of processing information within $form_state. | |
WidgetBase:: |
protected | function | Returns whether the widget handles multiple values. | |
WidgetBase:: |
public static | function |
Returns if the widget can be used for the provided field. Overrides WidgetInterface:: |
4 |
WidgetBase:: |
protected | function | Returns whether the widget used for default value form. | |
WidgetBase:: |
public static | function |
Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface:: |