JSON textareas can be validated and pretty-printed relatively simple in Drupal forms without third-party needs!
I made a first shot in the Posthog Drupal module (posthog_js submodule settings form).
Here are the Form class snippets:
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['init_config_json'] = [
'#type' => 'textarea',
'#title' => $this->t('Initialization configuration (JSON)'),
'#description' => $this->t("Posthog initialization JSON. Add values to override <a href=\"https://posthog.com/docs/libraries/js#config\" target=\"_blank\">the defaults</a>") . $accessJsSettingsWarning,
'#default_value' => $this->config('posthog_js.settings')->get('init_config_json') ?? "{}",
'#placeholder' => "{\n // autocapture: true,\n}",
'#disabled' => !$accessJsSettings,
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
try {
// Validate JSON:
$initConfigJson = trim($form_state->getValue('init_config_json') ?? '');
if (!empty($initConfigJson)) {
$form_state->setValue('init_config_json', json_encode(json_decode($initConfigJson ?: '{}', FALSE, 5, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE), JSON_FORCE_OBJECT | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
}
}
catch (\JsonException $e) {
$form_state->setErrorByName('init_config_json', $this->t('Invalid JSON'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->config('posthog_js.settings')
->set('init_config_json', $form_state->getValue('init_config_json'))
->save();
parent::submitForm($form, $form_state);
}
(https://git.drupalcode.org/project/posthog/-/blob/1.x/modules/posthog_j…)
Feel free to further improve it :) And buy me a coffee, if you liked it and it saved you time! ;)