Drupal 8 中的嵌套表单元素

问题描述 投票:0回答:2

我正在尝试通过执行以下操作将

checkboxes
元素包装在
details
中:

function pf_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $config = \Drupal::config('pf.settings.notifications');
    $form['pf'] = [
        '#type' => 'details',
        '#title' => t('Notification for updates in specific languages'),
        '#description' => t('Expect getting one to two emails weekly'),
        '#open': true,
    ];
    $form['pf']['pf.notifications.checkboxes'] = [
        '#type' => 'checkboxes',
        '#title' => t('Check the ones you\'d like to recieve!'),
        '#options' => [
            'de' => t('german'),
            'en' => t('english'),
        ],
        '#default_value' => [
            'de' => $config->get('de'),
            'en' => $config->get('en'),
        ],
    ];

    $form['actions']['submit']['#submit'][] = 'pf_form_user_form_submit';
}

但是提交后,我不断地回来

$values = ['de'=>0, 'en'=>0]

function pf_form_user_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $values = $form_state->getValue('pf.notifications.checkboxes');

    $config = \Drupal::config('pf.settings.notifications');
    $config
        ->set('de', $values['de'])
        ->set('en', $values['en'])
        ->save()
    ;
}

一旦我不使用包装

details
表单元素,数据(已检查元素的值==键)就在那里。像这样:

function pf_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    ....
    // $form['pf'] = [   commented out
    $form['pf.notifications.checkboxes'] = ...
    ....

使用调试器检查

$form_state
显示相同。第一种情况为零,第二种情况数据正常。

我错过了什么吗?表单元素分组如何工作?

drupal drupal-8 drupal-forms
2个回答
0
投票

我通过调试器更彻底地检查了

$form_state
,我注意到有些按键是原来的,带有点
'pf.notifications.checkboxes'
,而在其他地方,发生了下划线替换,按键是
'pf_notifications_checkboxes'

使用下划线。


0
投票

在“buildForm”函数中添加以下行

'#tree' => TRUE
© www.soinside.com 2019 - 2024. All rights reserved.