Score:1

Form builder not getting checkbox values

cn flag

I cannot determine why the form state seems to fail to get the values of the checkboxes on a form I'm building.

In my buildForm(), after submission, I am returning a result set. Each result that is built includes a checkbox form element.

$form['main_container']['grid'] = [ 
  '#type' => 'container',
];    

foreach ($title_list as $title => $row) {

  //...some code here...
  
  $form['main_container']['grid'][$row['div_id']] = [
    '#type' => 'fieldset',
    '#collapsible' => FALSE,
    '#attributes' => [
      'class' => [
        'grid-item-fieldset',
      ],
      'id' => $row['div_id'] . '-fieldset',
    ],
  ];
  
  $form['main_container']['grid'][$row['div_id']][$row['cn'] . '-selector'] = [
    '#type' => 'checkbox',
    '#return_value' => $row['div_id'],
    '#attributes' => [
      'class' => [
        'item-selector',
      ],
      'id' => $row['div_id'] . '-selector',
      'name' => 'cn-' . $row['cn'],
    ],
    '#default_value' => $row['div_id'],
  ];
}

With this rendering, I tried to get the value using $form_state->getValue($row['cn'] . '-selector); to get the value after submission and all I can get is NULL, despite the fact that the UI of the form confirms the boxes are checked.

I have also tried adding the #tree property to the 'grid' element (shown below), then using $form_state->getValue([$row['div_id'], $row['cn'] . '-selector']); and this also resulted in NULL.

$form['main_container']['grid'] = [ 
  '#type' => 'container',
  '#tree' => TRUE,
];

When I dump the $form_state->getValues() with Kint using Devel after the form's been rebuilt, I can see all the checkbox values, but they all have the value of 0, despite their value being set.

Does anyone have any insight into why I'm unable to get these values from the form state despite them existing in the form and being checked in the UI?

Score:1
ua flag

It's due to overriding the name attribute.

Drupal's $form_state relies on this name, so it needs to have the specific name that is automagically determined by the Form API.

Remove 'name' => 'cn-' . $row['cn'],

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.