You are here

public static function ServicePluginBase::validateJson in Analytics 8

Form element validation callback for a JSON textarea field.

Note that #required is validated by _form_validate() already.

File

src/Plugin/ServicePluginBase.php, line 204

Class

ServicePluginBase
Defines a base implementation for analytics service plugins will extend.

Namespace

Drupal\analytics\Plugin

Code

public static function validateJson(&$element, FormStateInterface $form_state) {
  $value = $element['#value'];
  if ($value === '') {
    return;
  }
  if (is_string($value)) {
    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
    $json = json_decode($value, TRUE);
    if ($error = json_last_error()) {
      $form_state
        ->setError($element, t('%name is not valid JSON: @error.', [
        '%name' => $name,
        '@error' => json_last_error_msg(),
      ]));
      return;
    }
  }
}