Drupal 8,如何构建分层表单?

时间:2015-11-21 19:27:24

标签: drupal-forms drupal-8

在Drupal 8中,我不明白如何构建“分层”形式。

我有这个样本表格

...
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['description']['subfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['description']['subsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['content'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['content']['subfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['content']['subsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    dpm($form_state->getValues(),"getValues");
}
...

enter image description here

当我提交表单时,我的form_state-> getValues()会返回:

enter image description here

form_state->getValues()仅包含['content']['subfirst']['content']['subsecond']值... 这意味着我必须使用api形式的唯一标签?我觉得很奇怪......

然后,我改变了我的形式:

$form['content']['subfirst'] become $form['content']['totosubfirst']

$form['content']['subsecond'] become $form['content']['todosubsecond']

新代码:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['description']['subfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['description']['subsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['content'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['content']['totosubfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['content']['totosubsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

当我提交表单时,我的form_state-> getValues()会返回:

enter image description here

我得到了四个值。但是,它们处于同一层级。我如何使用表单api获得这样的form_state:

'description' => 'subfirst' => string(3) "AAA"

'description' => 'subsecond' => string(3) "BBB"

'content' => 'totosubfirst' => string(3) "CCC"

'content' => 'totosubsecond' => string(3) "DDD"

?

我想获得一个分层的form_state,因为我想创建一个自定义函数,如:

foreach element in description
  do that
foreach element in content
  do that
...

1 个答案:

答案 0 :(得分:3)

The solution

设置#tree =>对于父元素为TRUE,则值将相应地嵌套