drupaldrupal-8drupal-forms

Nested form elements in Drupal 8


I'm trying to wrap checkboxes element in details by doing something like this:

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';
}

but on submit, I get constantly back $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()
    ;
}

As soon as I don't use the wrapping details form element, data (value==key for checked elements) is there. Like this:

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

Inspecting $form_state with debugger shows the same. Zeroes in first case, ok data in second.

Am I missing something? How does grouping of form elements work?


Solution

  • I inspected the $form_state through the debugger more thoroughly, and I noticed some of the keys were in original, with dots 'pf.notifications.checkboxes' while in other places, substitution for underscores took place and the key was 'pf_notifications_checkboxes'.

    Works with underscores.