1

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?

1 Answer 1

1

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'],

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.