首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在窗体中检索#树形值?

如何在窗体中检索#树形值?
EN

Drupal用户
提问于 2021-10-14 13:31:59
回答 2查看 452关注 0票数 0

我是Drupal 8的新手,我正在创建一个具有#tree表单的模块。我选择了#tree表单来创建具有相同文本字段和按钮的多个表单。

我在drupal中看到了一个关于#tree的文档。https://www.drupal.org/docs/7/api/form-api/tree-and-parents我已经对它进行了研究,没有找到任何关于如何从树中获取特定值的文档、帖子或博客。

我已经在我的表单中实现了#树。唯一的问题是我无法从表单中检索特定的值。

代码语言:javascript
复制
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与我的数据库中的行相关。这个过程是从用户那里获取名字和姓氏,这些变量将保存在数据库中。

我怎样才能在#树表格中得到第二个名字?

EN

回答 2

Drupal用户

发布于 2021-10-14 13:46:14

#tree表示表单中的层次结构,您仍然需要有效和逻辑的PHP才能使它工作。

代码语言:javascript
复制
// 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'];
票数 0
EN

Drupal用户

发布于 2021-10-14 18:32:13

#tree在表单的提交处理程序中创建值的层次结构。

比较:

代码语言:javascript
复制
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添加到容器中:

代码语言:javascript
复制
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元素)的一部分,需要相对于此检索:

代码语言:javascript
复制
// 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'])
票数 0
EN
页面原文内容由Drupal提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://drupal.stackexchange.com/questions/307630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档