You are here

public function YamlFormUiEntityForm::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 YamlFormEntityForm::validateForm

File

modules/yamlform_ui/src/YamlFormUiEntityForm.php, line 287

Class

YamlFormUiEntityForm
Base for controller for form UI.

Namespace

Drupal\yamlform_ui

Code

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

  /** @var \Drupal\yamlform\YamlFormInterface $yamlform */
  $yamlform = $this
    ->getEntity();

  // Don't validate new forms because they don't have any initial
  // elements.
  if ($yamlform
    ->isNew()) {
    return;
  }

  // Get raw flattened elements that will be used to rebuild element's YAML
  // hierarchy.
  $elements_flattened = $yamlform
    ->getElementsDecodedAndFlattened();

  // Get the reordered elements and sort them by weight.
  $elements_reordered = $form_state
    ->getValue('elements_reordered');
  uasort($elements_reordered, [
    'Drupal\\Component\\Utility\\SortArray',
    'sortByWeightElement',
  ]);

  // Make sure the reordered element keys and match the existing element keys.
  if (array_diff_key($elements_reordered, $elements_flattened)) {
    $form_state
      ->setError($form['elements_reordered'], $this
      ->t('The elements have been unexpectedly altered. Please try again'));
  }

  // Validate parent key and add children to ordered elements.
  foreach ($elements_reordered as $key => $table_element) {
    $parent_key = $table_element['parent_key'];

    // Validate the parent key.
    if ($parent_key && !isset($elements_flattened[$parent_key])) {
      $form_state
        ->setError($form['elements_reordered'], $this
        ->t('Parent %parent_key does not exist.', [
        '%parent_key' => $parent_key,
      ]));
      return;
    }

    // Set #required or remove the property.
    if (isset($elements_reordered[$key]['required'])) {
      if (empty($elements_reordered[$key]['required'])) {
        unset($elements_flattened[$key]['#required']);
      }
      else {
        $elements_flattened[$key]['#required'] = TRUE;
      }
    }

    // Add this key to the parent's children.
    $elements_reordered[$parent_key]['children'][$key] = $key;
  }

  // Rebuild elements to reflect new hierarchy.
  $elements_updated = [];

  // Preserve the original elements root properties.
  $elements_original = Yaml::decode($yamlform
    ->get('elements'));
  foreach ($elements_original as $key => $value) {
    if (Element::property($key)) {
      $elements_updated[$key] = $value;
    }
  }
  $this
    ->buildUpdatedElementsRecursive($elements_updated, '', $elements_reordered, $elements_flattened);

  // Update the form's elements.
  $yamlform
    ->setElements($elements_updated);
  parent::validateForm($form, $form_state);
}