You are here

public static function YamlFormCodeMirror::validateYamlFormCodeMirror in YAML Form 8

Form element validation handler for #type 'yamlform_codemirror'.

File

src/Element/YamlFormCodeMirror.php, line 109

Class

YamlFormCodeMirror
Provides a form element for HTML, YAML, or Plain text using CodeMirror.

Namespace

Drupal\yamlform\Element

Code

public static function validateYamlFormCodeMirror(&$element, FormStateInterface $form_state, &$complete_form) {
  if ($errors = static::getErrors($element, $form_state, $complete_form)) {
    $build = [
      'title' => [
        '#markup' => t('%title is not valid.', [
          '%title' => isset($element['#title']) ? $element['#title'] : t('YAML'),
        ]),
      ],
      'errors' => [
        '#theme' => 'item_list',
        '#items' => $errors,
      ],
    ];
    $form_state
      ->setError($element, \Drupal::service('renderer')
      ->render($build));
  }
  if ($element['#mode'] == 'yaml' && (isset($element['#default_value']) && is_array($element['#default_value']))) {

    // Handle rare case where single array value is not parsed correctly.
    if (preg_match('/^- (.*?)\\s*$/', $element['#value'], $match)) {
      $value = [
        $match[1],
      ];
    }
    else {
      $value = $element['#value'] ? Yaml::decode($element['#value']) : [];
    }
    $form_state
      ->setValueForElement($element, $value);
  }
}