我是Drupal 8的新手,我正在创建一个具有#tree表单的模块。我选择了#tree表单来创建具有相同文本字段和按钮的多个表单。
我在drupal中看到了一个关于#tree的文档。https://www.drupal.org/docs/7/api/form-api/tree-and-parents我已经对它进行了研究,没有找到任何关于如何从树中获取特定值的文档、帖子或博客。
我已经在我的表单中实现了#树。唯一的问题是我无法从表单中检索特定的值。
for($counter = 0; $counter < $rowCount; $counter++){
$form['firstname']['#tree'] = TRUE;
$form['firstname'] => [
'#type' => 'textfield',
'#title' => 'First name',
];
$form['secondname'] => [
'#type' => 'textfield',
'#title' => 'Second name',
];
$form['save'] => [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#submit' => ['::submitForm'],
];
}rowCount与我的数据库中的行相关。这个过程是从用户那里获取名字和姓氏,这些变量将保存在数据库中。
我怎样才能在#树表格中得到第二个名字?
发布于 2021-10-14 13:46:14
#tree表示表单中的层次结构,您仍然需要有效和逻辑的PHP才能使它工作。
// In the build...
$form['parent'] = [
'#type' => 'container',
'#tree' => TRUE,
];
for($counter = 0; $counter < $rowCount; $counter++){
$form['parent'][$counter] = [
'firstname' => ['#type' => 'input', ...],
'lastname' => ['#type' => 'input', ...],
];
}
// In the submit...
// '0' is the key you set with $counter previously.
$first_firstname = $form_state->getValue('parent')[0]['firstname'];
$first_lastname = $form_state->getValue('parent')[0]['lastname'];发布于 2021-10-14 18:32:13
#tree在表单的提交处理程序中创建值的层次结构。
比较:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['container'] = [
'#type' => 'container',
];
$form['container']['some_value'] = [
'#type' = >'textfield',
];
// Submit buttons etc. not shown
return $form;
}这将创建一个表单元素。单击submit后,使用form元素的键返回值。在这种情况下,关键是some_value,这意味着验证和提交处理程序可以使用form_state->getValue('some_value')检索提交的值。
现在,将#tree添加到容器中:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['container'] = [
'#type' => 'container',
'#tree' => TRUE,
];
$form['container']['some_value'] = [
'#type' = >'textfield',
];
// Submit buttons etc. not shown
return $form;
}通过此更改,$form_state->getValue('some_value')将不返回任何内容,因为该值现在是容器元素( #tree元素)的一部分,需要相对于此检索:
// Returns an array with a single key, 'some_value', that contains the
// submitted value.
$form_state->getValue('container')
// Returns the submitted value:
$form_state->getValue(['container', 'some_value'])https://drupal.stackexchange.com/questions/307630
复制相似问题