我试图允许用户使用ajax调用基于下拉框动态选择多个字段,但是之后似乎无法通过ajax调用来重建表单。
<?php
class AJAXexample extends BlockBase {
public function blockForm($form, FormStateInterface $form_state) {
if (empty($form_state->getValue('number'))) {
$form_state->setValue('number', 3);
}
$form['columnNum'] = [
'#title' => t('Number of Columns'),
'#type' => 'select',
'#options' => [
1 => '1',
2 => '2',
3 => '3',
4 => '4',
],
'#default_value' => $this->configuration['columnNum'],
'#empty_option' => t('-select-'),
'#ajax' => [
'callback' => [$this, 'columnCallback'],
],
];
for ($i = 0; $i < $form_state->getValue('number'); $i += 1) {
$form['column'][$i] = [
$i => [
'#type' => 'details',
'#title' => t('Column '.$numTitle),
'#open' => FALSE,
'columnTitle' => [
'#type' => 'textfield',
'#title' => t('Column Title'),
'#value' => $config[0]['columnTitle'],
],
],
];
return $form;
}
public function columnCallback(array &$form, FormStateInterface $form_state) {
$form_state->setValue('number', 10);
$form_state->setRebuild(true);
return $form;
}
}
文本字段的数量基于form_state变量“ number”。回调columnCallback将form_state变量更改为10,并且在更改'columnNum'表单字段时触发。但是,即使$ form_state-> setRebuild();也不会使用新的字段数来重建表单。叫做。有没有办法让ajax调用后重新生成表单?
注意:我已经尝试过诸如在实际的ajax调用中替换或附加表单项的技术,但是当发生这种情况时,替换字段中的任何输入都不会传递给$ form_state。
更新:尝试4k4的解决方案后,我收到一条错误
Recoverable fatal error: Argument 1 passed to Drupal\Core\Render\MainContent\AjaxRenderer::renderResponse() must be of the type array, null given, called in /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php on line 89 and defined in Drupal\Core\Render\MainContent\AjaxRenderer->renderResponse() (line 45 of /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php).
认为发生错误是因为$ form ['column']尽管在blockForm函数中被创建为容器,但仍返回null。我试图以其他方式调用回调
'#ajax' => [
'callback' => '::columnCallback',
]
和
'#ajax' => [
'callback' => [$this, '\Drupal\my_examples\Plugin\Block\AJAXexample::columnCallback'],
]
但是我收到同样的错误。奇怪的是,当我更改回调以返回整个$ form而不是仅返回$ form ['column']时,它会重复该表单(该表单的副本出现在当前表单下方)并且仍然没有适当的列数。