View source
<?php
namespace Drupal\high_contrast\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\high_contrast\HighContrastTrait;
class HighContrastSwitchForm extends FormBase {
use HighContrastTrait;
public function getFormId() {
return 'high_contrast_switch';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#cache']['contexts'][] = 'high_contrast';
$settings = [
'switcher_widget' => 'links',
'switcher_label' => 'Contrast:',
'high_label' => $this
->t('Enable'),
'separator' => '|',
'normal_label' => $this
->t('Disable'),
'use_ajax' => FALSE,
'toggle_element' => FALSE,
];
foreach ($settings as $key => $value) {
if (!empty($form_state
->getBuildInfo()['args'][0][$key])) {
$settings[$key] = $form_state
->getBuildInfo()['args'][0][$key];
}
}
$values = [
0 => $settings['normal_label'],
1 => $settings['high_label'],
];
if ($settings['switcher_widget'] == 'select' || $settings['switcher_widget'] == 'radios') {
$form['switch'] = [
'#type' => $settings['switcher_widget'],
'#options' => $values,
'#default_value' => $this
->highContrastEnabled() ? 1 : 0,
];
if ($settings['switcher_widget'] == 'radios' && $settings['toggle_element']) {
$form['switch']['#type'] = 'checkbox';
$form['switch']['#title'] = $settings['high_label'];
unset($form['switch']['#options']);
}
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Go',
];
if ($settings['use_ajax']) {
$form['switch']['#attributes'] = [
'onChange' => 'this.form.submit();',
];
$form['submit']['#attributes']['class'][] = 'js-hide';
}
}
else {
$current_url = Url::fromRoute('<current>')
->toString();
if (!$settings['toggle_element']) {
$form['enable_link'] = [
'#type' => 'link',
'#title' => $settings['high_label'],
'#url' => Url::fromRoute('high_contrast.enable', [], [
'query' => [
'destination' => $current_url,
],
]),
];
$form['disable_link'] = [
'#type' => 'link',
'#title' => $settings['normal_label'],
'#url' => Url::fromRoute('high_contrast.disable', [], [
'query' => [
'destination' => $current_url,
],
]),
];
}
else {
$route = $this
->highContrastEnabled() ? 'high_contrast.disable' : 'high_contrast.enable';
$form['toggle_link'] = [
'#type' => 'link',
'#title' => $this
->highContrastEnabled() ? $settings['normal_label'] : $settings['high_label'],
'#url' => Url::fromRoute($route, [], [
'query' => [
'destination' => $current_url,
],
]),
];
}
}
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($form_state
->getValue('switch') == 1) {
$this
->enableHighContrast();
}
else {
$this
->disableHighContrast();
}
}
}