You are here

public function DirectoryBrowser::validate in Media Directories 8

Same name and namespace in other branches
  1. 3.x modules/media_directories_ui/src/Plugin/EntityBrowser/Widget/DirectoryBrowser.php \Drupal\media_directories_ui\Plugin\EntityBrowser\Widget\DirectoryBrowser::validate()
  2. 2.x modules/media_directories_ui/src/Plugin/EntityBrowser/Widget/DirectoryBrowser.php \Drupal\media_directories_ui\Plugin\EntityBrowser\Widget\DirectoryBrowser::validate()

File

modules/media_directories_ui/src/Plugin/EntityBrowser/Widget/DirectoryBrowser.php, line 285

Class

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

Namespace

Drupal\media_directories_ui\Plugin\EntityBrowser\Widget

Code

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!'));
  }
}