You are here

class DirectoryBrowserUiForm in Media Directories 3.x

Uses a view to provide entity listing in a browser's widget.

Hierarchy

Expanded class hierarchy of DirectoryBrowserUiForm

File

modules/media_directories_ui/src/Form/DirectoryBrowserUiForm.php, line 17

Namespace

Drupal\media_directories_ui\Form
View source
class DirectoryBrowserUiForm extends FormBase {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('event_dispatcher'), $container
      ->get('entity_type.manager'), $container
      ->get('current_user'));
  }

  /**
   * Constructs a new View object.
   *
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   Event dispatcher service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user) {
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, MediaDirectoriesLibraryState $state = NULL) {

    // Default values.
    $form['#attached']['drupalSettings']['media_directories']['cardinality'] = -1;
    $form['#attached']['drupalSettings']['media_directories']['target_bundles'] = [];
    $form['browser'] = [
      '#theme' => 'media_directories_browser',
    ];
    $form['browser']['active_directory'] = [
      '#type' => 'hidden',
      '#default_value' => MEDIA_DIRECTORY_ROOT,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this
        ->t('Insert selected'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validate(array &$form, FormStateInterface $form_state) {
    $user_input = $form_state
      ->getUserInput();
    if (isset($user_input['entity_browser_select'])) {
      $selected_rows = array_values(array_filter($user_input['entity_browser_select']));
      foreach ($selected_rows as $row) {

        // Verify that the user input is a string and split it.
        // Each $row is in the format entity_type:id.
        if (is_string($row) && ($parts = explode(':', $row, 2))) {

          // Make sure we have a type and id present.
          if (count($parts) == 2) {
            try {
              $storage = $this->entityTypeManager
                ->getStorage($parts[0]);
              if (!$storage
                ->load($parts[1])) {
                $message = $this
                  ->t('The @type Entity @id does not exist.', [
                  '@type' => $parts[0],
                  '@id' => $parts[1],
                ]);
                $form_state
                  ->setError($form['widget']['view']['entity_browser_select'], $message);
              }
            } catch (PluginNotFoundException $e) {
              $message = $this
                ->t('The Entity Type @type does not exist.', [
                '@type' => $parts[0],
              ]);
              $form_state
                ->setError($form['widget']['view']['entity_browser_select'], $message);
            }
          }
        }
      }

      // If there weren't any errors set, run the normal validators.
      if (empty($form_state
        ->getErrors())) {
        parent::validate($form, $form_state);
      }
    }
    else {
      $form_state
        ->setError($form, $this
        ->t('Please select media element!'));
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
    $selected_rows = array_values(array_filter($form_state
      ->getUserInput()['entity_browser_select']));
    $entities = [];
    foreach ($selected_rows as $row) {
      list($type, $id) = explode(':', $row);
      $storage = $this->entityTypeManager
        ->getStorage($type);
      if ($entity = $storage
        ->load($id)) {
        $entities[] = $entity;
      }
    }
    return $entities;
  }

  /**
   * {@inheritdoc}
   */
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
    $entities = $this
      ->prepareEntities($form, $form_state);
    $this
      ->selectEntities($entities, $form_state);
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues()['table'][$this
      ->uuid()]['form'];
    $this->configuration['submit_text'] = $values['submit_text'];
    $this->configuration['auto_select'] = $values['auto_select'];
  }

  /**
   * Returns a unique string identifying the form.
   *
   * The returned ID should be a unique string that can be a valid PHP function
   * name, since it's used in hook implementation names such as
   * hook_form_FORM_ID_alter().
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'directory_browser_form';
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // TODO: Implement submitForm() method.
  }

}

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
DirectoryBrowserUiForm::$currentUser protected property The current user.
DirectoryBrowserUiForm::$entityTypeManager protected property
DirectoryBrowserUiForm::buildConfigurationForm public function
DirectoryBrowserUiForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
DirectoryBrowserUiForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DirectoryBrowserUiForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DirectoryBrowserUiForm::prepareEntities protected function
DirectoryBrowserUiForm::submit public function
DirectoryBrowserUiForm::submitConfigurationForm public function
DirectoryBrowserUiForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DirectoryBrowserUiForm::validate public function
DirectoryBrowserUiForm::__construct public function Constructs a new View object.
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 72
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.