easychart-8.x-3.5/src/Form/TemplatesForm.php
src/Form/TemplatesForm.php
<?php
namespace Drupal\easychart\Form;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Form\FormStateInterface;
/**
* Templates form.
*/
class TemplatesForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'easychart_admin_templates_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames(): array {
return [
'easychart.settings',
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL): array {
$config = $this->config('easychart.settings');
$form['#attached']['library'][] = 'easychart/easychart.admin';
$form['#attached']['library'][] = 'easychart/lib.easycharts.full';
$form['#attached']['library'][] = 'easychart/lib.highcharts';
$default = $config->get('templates');
if (!empty($default)) {
$default = json_encode(Json::decode($config->get('templates')), JSON_PRETTY_PRINT);
}
$form['templates'] = [
'#type' => 'textarea',
'#title' => $this->t('Templates'),
'#title_display' => 'invisible',
'#default_value' => $default,
'#description' => $this->t("These templates will be selectable in the Easychart interface when creating/editing a chart."),
'#attributes' => ['class' => ['easychart-templates']],
'#rows' => 30,
];
$form['actions']['reset'] = [
'#type' => 'submit',
'#value' => $this->t('Reset to defaults'),
'#submit' => ['::resetForm'],
'#limit_validation_errors' => [],
'#weight' => 100,
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$templates = $form_state->getValue('templates');
if (!empty($templates)) {
$json = Json::decode($templates);
if ($json === NULL) {
$form_state->setError($form['templates'], 'The templates value must be valid JSON.');
}
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$templates = $form_state->getValue('templates');
if (!empty($templates)) {
$templates = Json::encode(Json::decode($templates));
}
$this->config('easychart.settings')
->set('templates', $templates)
->save();
}
/**
* Redirect to reset form.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public function resetForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('easychart.reset_templates_confirm_form');
}
}
