You are here

public function View::validate in Entity Browser 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityBrowser/Widget/View.php \Drupal\entity_browser\Plugin\EntityBrowser\Widget\View::validate()

Validates form.

Parameters

array $form: Form.

\Drupal\Core\Form\FormStateInterface $form_state: Form state object.

Overrides WidgetBase::validate

File

src/Plugin/EntityBrowser/Widget/View.php, line 165

Class

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

Namespace

Drupal\entity_browser\Plugin\EntityBrowser\Widget

Code

public function validate(array &$form, FormStateInterface $form_state) {
  $user_input = $form_state
    ->getUserInput();
  if (isset($user_input['entity_browser_select'])) {
    if (is_array($user_input['entity_browser_select'])) {
      $selected_rows = array_values(array_filter($user_input['entity_browser_select']));
    }
    else {
      $selected_rows = [
        $user_input['entity_browser_select'],
      ];
    }
    $use_field_cardinality = !empty($user_input['entity_browser_select_form_metadata']['use_field_cardinality']);
    if ($use_field_cardinality) {
      $cardinality = !empty($user_input['entity_browser_select_form_metadata']['cardinality']) ? $user_input['entity_browser_select_form_metadata']['cardinality'] : 0;
      if ($cardinality > 0 && count($selected_rows) > $cardinality) {
        $message = $this
          ->formatPlural($cardinality, 'You can only select one item.', 'You can only select up to @number items.', [
          '@number' => $cardinality,
        ]);
        $form_state
          ->setError($form['widget']['view']['entity_browser_select'], $message);
      }
    }
    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);
    }
  }
}