关于 drupal-form-api
面向 Drupal 开发者的 Form API 参考,示例涵盖普通表单和配置表单的结构。还列出常见表单元素及其用途。
主要功能
- 01创建 FormBase 表单
- 02创建 ConfigFormBase 配置表单
- 03实现配置名称和表单 ID
- 04参考常见表单元素
适用场景
- 01构建模块交互表单
- 02创建模块设置页面
- 03选择适合的数据输入元素
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-form-api安装后在 Claude Code 中输入/drupal-form-api确认已加载。
附带文件README.md
README 原文English
来自项目 READMEREADME 暂无中文译文,以下为英文原文;中文介绍见上方。
Drupal Form API
Simple Form (FormBase)
// src/Form/MyForm.php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class MyForm extends FormBase {
public function __construct(
private readonly EntityTypeManagerInterface $entityTypeManager,
) {}
public static function create(ContainerInterface $container): static {
return new static(
$container->get('entity_type.manager'),
);
}
public function getFormId(): string {
return 'my_module_my_form';
}
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['name'] = [
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state): void {
$name = $form_state->getValue('name');
$this->messenger()->addStatus($this->t('Hello @name!', ['@name' => $name]));
}
}
Config Form (ConfigFormBase)
final class MySettingsForm extends ConfigFormBase {
protected function getEditableConfigNames(): array {
return ['my_module.settings'];
}
public function getFormId(): string {
return 'my_module_settings';
}
public function buildForm(array $form, FormStateInterface $form_state): array {
$config = $this->config('my_module.settings');
$form['enabled'] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable feature'),
'#default_value' => $config->get('enabled'),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->config('my_module.settings')
->set('enabled', $form_state->getValue('enabled'))
->save();
parent::submitForm($form, $form_state);
}
}
Common Form Elements
| Type | Description |
|---|---|
textfield | Single line text |
textarea | Multi-line text |
select | Dropdown |
checkboxes | Multiple checkboxes |
radios | Radio buttons |
checkbox | Single checkbox |
number | Numeric input |
email | Email input |
managed_file | Managed file upload |
entity_autocomplete | Entity reference autocomplete |
date | Date picker |
details | Collapsible group |
container | Non-visual wrapper |
hidden | Hidden field |
submit | Submit button |
评论
支持 Markdown