The checkbox with name/key 0 is always registered in $form_values as if it was selected by the user. I hope the following bit of code would explain this better.

Given checkboxes '0', 'A' and 'B'. Let's assume the user selected the 3 of them. After submission, this is how they will look in $form_values:

    [0] => 0
    [A] => A
    [B] => B

Now assume none of them was selected, this is how they will look like in $form_values:

    [0] => 0
    [A] => 0
    [B] => 0

[0] = 0 here is the same in both cases, which seems to fool FAPI that the element was selected even if it wasn't.

Internally, this seems to be a checkbox element issue, but it will unlikely occur unless it was used in the context of checkboxes element. (who will intentionally call a checkbox '0' anyway :P)

Btw, if you want to reproduce this quickly you can try this:

$form['foo'] = array(
  '#title' => 'Checkboxes test',
  '#type' => 'checkboxes',
  '#options' => array(
    0 => 'A',
    1 => 'B',
  ),
  '#default_value' => array(
    0 => 0,
    1 => 0,
  ),
);

Here the option with key 0 ('A') will always be checked.

P.S. I stumbled upon that issue when I was trying to use checkboxes with the options array of the watchdog severity levels (WATCHDOG_EMERG => 0) here.

Comments

sutharsan’s picture

Status: Active » Closed (works as designed)

This is by design as you can read in the Forms API reference on checkboxes "The #options array can not have a 0 key, as it would not be possible to discern checked and unchecked states.". However you are not the only one stumbling with the '0'.

AmrMostafa’s picture

Status: Closed (works as designed) » Active

I don't think this is acceptable as Drupal core has lists of items that are numbered starting from 0 so generating checkboxes for these wouldn't be possible then (unless you do some ugyl hacks), example is the recently added watchdog severity list. I think this should be fixed, if it's not a bug report please set it to feature request. But IMHO it's a bug that needs to be fixed.

With major help from chx, I had a patch for this in the works, I will re-roll it for HEAD soon.

chx’s picture

Status: Active » Closed (works as designed)

Acceptable or not but please fix HTML.

KingMoore’s picture

oh man this SERIOUSLY did my head in for most of today.

fat_mike’s picture

mine too