cache_monitor-1.0.x-dev/src/Form/SettingsForm.php

src/Form/SettingsForm.php
<?php
# File: site/web/modules/custom/cache_monitor/src/Form/SettingsForm.php

namespace Drupal\cache_monitor\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Settings form using State API (non-deployable) for metrics toggle.
 */
class SettingsForm extends FormBase {

  public function getFormId(): string {
    return 'cache_monitor_settings_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state): array {
    $enabled = \Drupal::state()->get('cache_monitor.metrics_enabled', FALSE);

    // Stored as array in state; convert to newline list.
    $stored_paths = \Drupal::state()->get('cache_monitor.paths', []);
    if (!is_array($stored_paths)) {
      $stored_paths = [];
    }

    $form['metrics_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable metrics collection'),
      '#default_value' => $enabled,
      '#description' => $this->t('Uncheck to stop collecting cache timing metrics (state is not exported).'),
    ];

    $form['paths'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Paths to monitor'),
      '#default_value' => implode("\n", $stored_paths),
      '#description' => $this->t('Enter one internal path per line (example: node/1, user/login). Leave empty for all paths. Do not include the leading slash.'),
      '#rows' => 5,
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
    ];

    return $form;
  }


  public function validateForm(array &$form, FormStateInterface $form_state): void {
    $raw = (string) $form_state->getValue('paths');
    $lines = preg_split('/\R/', $raw) ?: [];
    $clean = [];
    foreach ($lines as $line) {
      $line = trim($line);
      if ($line === '') {
        continue;
      }
      // Normalize: strip leading slash for consistency.
      $line = ltrim($line, '/');
      if ($line !== '') {
        $clean[] = $line;
      }
    }
    $form_state->setValue('paths', $clean);
  }

  public function submitForm(array &$form, FormStateInterface $form_state): void {
    \Drupal::state()->set('cache_monitor.metrics_enabled', (bool) $form_state->getValue('metrics_enabled'));
    \Drupal::state()->set('cache_monitor.paths', $form_state->getValue('paths'));
    $this->messenger()->addStatus($this->t('Settings saved.'));
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc