关于 drupal-form-ajax
用于构建 Drupal AJAX 表单的开发技能,介绍回调模式、AjaxResponse 命令、AJAX 属性和表单重建。
主要功能
- 01AJAX 回调模式
- 02AjaxResponse 命令用法
- 03包装器与事件配置
- 04表单重建处理
适用场景
- 01选择后更新表单选项
- 02异步替换或修改页面元素
- 03配置进度指示器与效果
- 04提交后重建表单
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-form-ajax安装后在 Claude Code 中输入/drupal-form-ajax确认已加载。
附带文件README.md
README 原文English
来自项目 READMEREADME 暂无中文译文,以下为英文原文;中文介绍见上方。
Drupal AJAX Forms
AJAX Callback Pattern
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['type'] = [
'#type' => 'select',
'#title' => $this->t('Type'),
'#options' => ['a' => 'Type A', 'b' => 'Type B'],
'#ajax' => [
'callback' => '::updateOptions',
'wrapper' => 'options-wrapper',
'event' => 'change',
],
];
$form['options_wrapper'] = [
'#type' => 'container',
'#attributes' => ['id' => 'options-wrapper'],
];
$type = $form_state->getValue('type', 'a');
$form['options_wrapper']['value'] = [
'#type' => 'textfield',
'#title' => $this->t('Value for @type', ['@type' => $type]),
];
return $form;
}
public function updateOptions(array &$form, FormStateInterface $form_state): array {
return $form['options_wrapper'];
}
AjaxResponse with Commands
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\MessageCommand;
public function ajaxCallback(array &$form, FormStateInterface $form_state): AjaxResponse {
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-wrapper', $form['my_element']));
$response->addCommand(new HtmlCommand('#message', $this->t('Updated!')));
$response->addCommand(new InvokeCommand('#my-input', 'val', ['new value']));
$response->addCommand(new MessageCommand($this->t('Success!'), NULL, ['type' => 'status']));
return $response;
}
#ajax Properties
'#ajax' => [
'callback' => '::myCallback', // Method or [ClassName, 'method']
'wrapper' => 'wrapper-id', // DOM ID to replace/update
'event' => 'change', // JS event (change, click, blur, etc.)
'method' => 'replaceWith', // replaceWith, append, prepend, etc.
'effect' => 'fade', // none, slide, fade
'progress' => [
'type' => 'throbber', // throbber or bar
'message' => NULL,
],
'url' => NULL, // Custom URL (leave NULL for default)
'options' => [], // Additional jQuery.ajax options
],
Trigger Form Rebuild
public function submitForm(array &$form, FormStateInterface $form_state): void {
$form_state->setRebuild(TRUE);
}
评论
支持 Markdown