You are here

public function YamlFormUiElementFormBase::validateForm in YAML Form 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

modules/yamlform_ui/src/Form/YamlFormUiElementFormBase.php, line 240

Class

YamlFormUiElementFormBase
Provides a base class for form element forms.

Namespace

Drupal\yamlform_ui\Form

Code

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

  // Only validate the submit button.
  $button = $form_state
    ->getTriggeringElement();
  if (empty($button['#_validate_form'])) {
    return;
  }

  // The form element configuration is stored in the 'properties' key in
  // the form, pass that through for validation.
  $element_form_state = clone $form_state;
  $element_form_state
    ->setValues($form_state
    ->getValue('properties'));

  // Validate configuration form.
  $yamlform_element = $this
    ->getYamlFormElement();
  $yamlform_element
    ->validateConfigurationForm($form, $element_form_state);

  // Get errors for element validation.
  $element_errors = $element_form_state
    ->getErrors();
  foreach ($element_errors as $element_error) {
    $form_state
      ->setErrorByName(NULL, $element_error);
  }

  // Stop validation is the element properties has any errors.
  if ($form_state
    ->hasAnyErrors()) {
    return;
  }

  // Set element properties.
  $properties = $yamlform_element
    ->getConfigurationFormProperties($form, $element_form_state);
  $parent_key = $form_state
    ->getValue('parent_key');
  $key = $form_state
    ->getValue('key');
  if ($key) {
    $this->yamlform
      ->setElementProperties($key, $properties, $parent_key);

    // Validate elements.
    if ($messages = $this->elementsValidator
      ->validate($this->yamlform)) {
      $t_args = [
        ':href' => Url::fromRoute('entity.yamlform.source_form', [
          'yamlform' => $this->yamlform
            ->id(),
        ])
          ->toString(),
      ];
      $form_state
        ->setErrorByName('elements', $this
        ->t('There has been error validating the elements. You may need to edit the <a href=":href">YAML source</a> to resolve the issue.', $t_args));
      foreach ($messages as $message) {
        drupal_set_message($message, 'error');
      }
    }
  }
}