You are here

public function IndexFieldsForm::validateForm in Search API 8

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

src/Form/IndexFieldsForm.php, line 406

Class

IndexFieldsForm
Provides a form for configuring the fields of a search index.

Namespace

Drupal\search_api\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $field_values = $form_state
    ->getValue('fields', []);
  $new_ids = [];
  foreach ($field_values as $field_id => $field) {
    $new_id = $field['id'];
    $new_ids[$new_id][] = $field_id;

    // Check for reserved and other illegal field IDs.
    if ($this->fieldsHelper
      ->isFieldIdReserved($new_id)) {
      $args = [
        '%field_id' => $new_id,
      ];
      $error = $this
        ->t('%field_id is a reserved value and cannot be used as the machine name of a normal field.', $args);
      $form_state
        ->setErrorByName('fields][' . $field_id . '][id', $error);
    }
    elseif (preg_match('/^_+$/', $new_id)) {
      $error = $this
        ->t('Field IDs have to contain non-underscore characters.');
      $form_state
        ->setErrorByName('fields][' . $field_id . '][id', $error);
    }
    elseif (preg_match('/[^a-z0-9_]/', $new_id)) {
      $error = $this
        ->t('Field IDs must contain only lowercase letters, numbers and underscores.');
      $form_state
        ->setErrorByName('fields][' . $field_id . '][id', $error);
    }
  }

  // Identify duplicates.
  $has_duplicates = function (array $old_ids) {
    return count($old_ids) > 1;
  };
  foreach (array_filter($new_ids, $has_duplicates) as $new_id => $old_ids) {
    $args['%field_id'] = $new_id;
    $error = $this
      ->t('Field ID %field_id is used multiple times. Field IDs must be unique.', $args);
    foreach ($old_ids as $field_id) {
      $form_state
        ->setErrorByName('fields][' . $field_id . '][id', $error);
    }
  }
}