ZF-2750: Zend_Form_Element_Checkbox - setValue inconsistent with getValue

Description

When using Zend_Form_Element_Checkbox elements, getValue returns either 1 (checked) or 0 (unchecked). I find that great. However, the current setValue works differently:


public function setValue($value)
{
    $value = ($value === null) ? 0 : 1;
    $this->checked = ($value === 0) ? false : true;
    return parent::setValue($value);
}

Anything other than null, sets the checkbox value to 1 (even 0 or '0'). I would suggest keeping it consistent with getValue, something along these lines:


public function setValue($value)
{
    if ($value === null) $value = 0;
    $this->checked = ($value == 0) ? false : true;
    return parent::setValue($value);
}

I would also suggest allowing the value to be a string ('0' or '1') -> thus a ==. This will allow populating with the data straight from the DB.

Comments

This is one symptom of multiple issues with checkboxes. I will be fixing these for the 1.5.0GA release.

All checkbox issues are corrected in trunk and 1.5 release branch.

Notes:

  • Set value of element when checked using setCheckedValue()
  • Set value of element when unchecked using setUncheckedValue()
  • setValue() then checks the submitted value against the checkedValue; if equal, that value is set; if not, the uncheckedValue is used. The checked property is then set accordingly
  • setChecked() will call setValue with either the checked or unchecked value based on the value of the flag
  • ViewHelper decorator always uses checked value to populate the form input (and uses the 'checked' property to determine whether or not it is on)