You are here

class Upload in Entity Browser 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityBrowser/Widget/Upload.php \Drupal\entity_browser\Plugin\EntityBrowser\Widget\Upload

Adds an upload field browser's widget.

Plugin annotation


@EntityBrowserWidget(
  id = "upload",
  label = @Translation("Upload"),
  description = @Translation("Adds an upload field browser's widget."),
  auto_select = FALSE
)

Hierarchy

Expanded class hierarchy of Upload

1 string reference to 'Upload'
entity_browser.browser.test_dropdown.yml in tests/modules/entity_browser_test/config/install/entity_browser.browser.test_dropdown.yml
tests/modules/entity_browser_test/config/install/entity_browser.browser.test_dropdown.yml

File

src/Plugin/EntityBrowser/Widget/Upload.php, line 26

Namespace

Drupal\entity_browser\Plugin\EntityBrowser\Widget
View source
class Upload extends WidgetBase {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * Upload constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   Event dispatcher service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
   *   The Widget Validation Manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager, ModuleHandlerInterface $module_handler, Token $token) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_type_manager, $validation_manager);
    $this->moduleHandler = $module_handler;
    $this->token = $token;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('event_dispatcher'), $container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.entity_browser.widget_validation'), $container
      ->get('module_handler'), $container
      ->get('token'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'upload_location' => 'public://',
      'multiple' => TRUE,
      'submit_text' => $this
        ->t('Select files'),
      'extensions' => 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp',
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
    $form = parent::getForm($original_form, $form_state, $additional_widget_parameters);
    $field_cardinality = $form_state
      ->get([
      'entity_browser',
      'validators',
      'cardinality',
      'cardinality',
    ]);
    $upload_validators = $form_state
      ->has([
      'entity_browser',
      'widget_context',
      'upload_validators',
    ]) ? $form_state
      ->get([
      'entity_browser',
      'widget_context',
      'upload_validators',
    ]) : [];
    $form['upload'] = [
      '#type' => 'managed_file',
      '#title' => $this
        ->t('Choose a file'),
      '#title_display' => 'invisible',
      '#upload_location' => $this->token
        ->replace($this->configuration['upload_location']),
      // Multiple uploads will only be accepted if the source field allows
      // more than one value.
      '#multiple' => $field_cardinality != 1 && $this->configuration['multiple'],
      '#upload_validators' => array_merge([
        'file_validate_extensions' => [
          $this->configuration['extensions'],
        ],
      ], $upload_validators),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
    $files = [];
    foreach ($form_state
      ->getValue([
      'upload',
    ], []) as $fid) {
      $files[] = $this->entityTypeManager
        ->getStorage('file')
        ->load($fid);
    }
    return $files;
  }

  /**
   * {@inheritdoc}
   */
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
    if (!empty($form_state
      ->getTriggeringElement()['#eb_widget_main_submit'])) {
      $files = $this
        ->prepareEntities($form, $form_state);
      array_walk($files, function (FileInterface $file) {
        $file
          ->setPermanent();
        $file
          ->save();
      });
      $this
        ->selectEntities($files, $form_state);
      $this
        ->clearFormValues($element, $form_state);
    }
  }

  /**
   * Clear values from upload form element.
   *
   * @param array $element
   *   Upload form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   */
  protected function clearFormValues(array &$element, FormStateInterface $form_state) {

    // We propagated entities to the other parts of the system. We can now remove
    // them from our values.
    $form_state
      ->setValueForElement($element['upload']['fids'], '');
    NestedArray::setValue($form_state
      ->getUserInput(), $element['upload']['fids']['#parents'], '');
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['upload_location'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Upload location'),
      '#default_value' => $this->configuration['upload_location'],
    ];
    $form['multiple'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Accept multiple files'),
      '#default_value' => $this->configuration['multiple'],
      '#description' => $this
        ->t('Multiple uploads will only be accepted if the source field allows more than one value.'),
    ];
    $form['extensions'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Allowed file extensions'),
      '#description' => $this
        ->t('Separate extensions with a space or comma and do not include the leading dot.'),
      '#default_value' => $this->configuration['extensions'],
      '#element_validate' => [
        [
          static::class,
          'validateExtensions',
        ],
      ],
      '#required' => TRUE,
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['token_help'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          'file',
        ],
      ];
      $form['upload_location']['#description'] = $this
        ->t('You can use tokens in the upload location.');
    }
    return $form;
  }

  /**
   * Validates a list of file extensions.
   *
   * @See \Drupal\file\Plugin\Field\FieldType\FileItem::validateExtensions
   */
  public static function validateExtensions($element, FormStateInterface $form_state) {
    if (!empty($element['#value'])) {
      $extensions = preg_replace('/([, ]+\\.?)/', ' ', trim(strtolower($element['#value'])));
      $extensions = array_filter(explode(' ', $extensions));
      $extensions = implode(' ', array_unique($extensions));
      if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) {
        $form_state
          ->setError($element, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.'));
      }
      else {
        $form_state
          ->setValueForElement($element, $extensions);
      }
    }
  }

}

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
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.
PluginConfigurationFormTrait::submitConfigurationForm public function Implements PluginFormInterface::submitConfigurationForm(). 3
PluginConfigurationFormTrait::validateConfigurationForm public function Implements PluginFormInterface::validateConfigurationForm(). 2
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.
Upload::$moduleHandler protected property The module handler service.
Upload::$token protected property The token service.
Upload::buildConfigurationForm public function Implements PluginFormInterface::buildConfigurationForm(). Overrides WidgetBase::buildConfigurationForm
Upload::clearFormValues protected function Clear values from upload form element.
Upload::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
Upload::defaultConfiguration public function Gets default configuration for this plugin. Overrides WidgetBase::defaultConfiguration
Upload::getForm public function Returns widget form. Overrides WidgetBase::getForm
Upload::prepareEntities protected function Prepares the entities without saving them. Overrides WidgetBase::prepareEntities
Upload::submit public function Submits form. Overrides WidgetBase::submit
Upload::validateExtensions public static function Validates a list of file extensions.
Upload::__construct public function Upload constructor. Overrides WidgetBase::__construct
WidgetBase::$entityTypeManager protected property Entity type manager service.
WidgetBase::$eventDispatcher protected property Event dispatcher service.
WidgetBase::$id protected property Plugin id.
WidgetBase::$label protected property Plugin label.
WidgetBase::$uuid protected property Plugin uuid.
WidgetBase::$validationManager protected property The Widget Validation Manager service.
WidgetBase::$weight protected property Plugin weight.
WidgetBase::access public function Defines if the widget is visible / accessible in a given context. Overrides WidgetInterface::access 3
WidgetBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
WidgetBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WidgetBase::getWeight public function Returns the widget's weight. Overrides WidgetInterface::getWeight
WidgetBase::handleWidgetContext protected function Allow configuration overrides at runtime based on widget context passed to this widget from the Entity Browser element.
WidgetBase::id public function Returns the widget id. Overrides WidgetInterface::id
WidgetBase::label public function Returns the widget label. Overrides WidgetInterface::label
WidgetBase::requiresJsCommands public function Returns if widget requires JS commands support by selection display. Overrides WidgetInterface::requiresJsCommands
WidgetBase::runWidgetValidators protected function Run widget validators.
WidgetBase::selectEntities protected function Dispatches event that informs all subscribers about new selected entities.
WidgetBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WidgetBase::setLabel public function Sets the widget's label. Overrides WidgetInterface::setLabel
WidgetBase::setWeight public function Sets the widget's weight. Overrides WidgetInterface::setWeight
WidgetBase::uuid public function Returns the widget UUID. Overrides WidgetInterface::uuid
WidgetBase::validate public function Validates form. Overrides WidgetInterface::validate 1