Skip to content

Instantly share code, notes, and snippets.

@drubb
Last active November 28, 2023 12:21
Show Gist options
  • Save drubb/5282d88279cd7e99c7f18d85d5543357 to your computer and use it in GitHub Desktop.
Save drubb/5282d88279cd7e99c7f18d85d5543357 to your computer and use it in GitHub Desktop.
Simplified Drupal config forms since Drupal 10.2
<?php declare(strict_types = 1);
namespace Drupal\my_module\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\RedundantEditableConfigNamesTrait;
/**
* Configure mymodule settings for this site.
*/
final class MyModuleSettingsForm extends ConfigFormBase {
use RedundantEditableConfigNamesTrait;
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'my_module_settings';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['example'] = [
'#type' => 'textfield',
'#title' => $this->t('Example'),
'#config_target' => new ConfigTarget(
'mymodule.settings',
'example',
toConfig: static::class . '::normalize'
),
];
return parent::buildForm($form, $form_state);
}
/**
* This example callback modifies the config value before it is stored (toConfig).
*/
public static function normalize(string $value): string {
return mb_strtoupper(trim($value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment