You are here

public function DomainPathForm::validateForm in Domain Path 8

Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level validation handler, otherwise an exception will be thrown.

Overrides ContentEntityForm::validateForm

File

src/Form/DomainPathForm.php, line 108

Class

DomainPathForm
Form controller for the domain_path entity edit forms.

Namespace

Drupal\domain_path\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {

  // Validation is optional.
  parent::validateForm($form, $form_state);
  $domains = $this->entityTypeManager
    ->getStorage('domain')
    ->loadMultipleSorted();
  $domain_id_value = $form_state
    ->getValue('domain_id');
  $domain_id = isset($domain_id_value[0]['target_id']) ? $domain_id_value[0]['target_id'] : NULL;
  $source_value = $form_state
    ->getValue('source');
  $source = isset($source_value[0]['value']) ? $source_value[0]['value'] : NULL;
  $source_check = rtrim(trim($source), " \\/");
  if ($source_check && $source_check[0] !== '/') {
    $form_state
      ->setErrorByName('source', $this
      ->t('Domain path "%source" needs to start with a slash.', [
      '%source' => $source_check,
    ]));
  }
  $alias_value = $form_state
    ->getValue('alias');
  $alias = isset($alias_value[0]['value']) ? $alias_value[0]['value'] : NULL;
  $alias_check = rtrim(trim($alias), " \\/");
  if ($alias_check && $alias_check[0] !== '/') {
    $form_state
      ->setErrorByName('alias', $this
      ->t('Domain path "%alias" needs to start with a slash.', [
      '%alias' => $alias_check,
    ]));
  }

  /** @var \Drupal\domain_path\Entity\DomainPath $current_domain_path */
  $current_domain_path = $form_state
    ->getformObject()
    ->getEntity();
  if ($domain_path_entity_data = $this->entityTypeManager
    ->getStorage('domain_path')
    ->loadByProperties([
    'alias' => $alias_check,
  ])) {
    foreach ($domain_path_entity_data as $domain_path_entity) {
      $check_domain_id = $domain_path_entity
        ->get('domain_id')->target_id;
      $is_same = $current_domain_path && $domain_path_entity
        ->id() == $current_domain_path
        ->id();
      if ($check_domain_id == $domain_id && !$is_same) {
        $domain_path = $domains[$domain_id]
          ->getPath();
        $form_state
          ->setErrorByName('alias', $this
          ->t('Domain path %path matches an existing domain path alias for %domain_path.', [
          '%path' => $alias_check,
          '%domain_path' => $domain_path,
        ]));
      }
    }
  }
  $alias_value[0]['value'] = $alias_check;
  $form_state
    ->setValue('alias', $alias_value);
}