4
votes

I've got this form element:

$form->input('ChecklistResponseGovernmentInfo.driversLicenseIsOnline', array('type'=>'radio', 'empty'=> true, 'options'=>array(0 => 'No', 1 => 'Yes')))

This is the validation rule for it:

'driversLicenseIsOnline' => array(
    'boolean' => array(
        'rule' => array('boolean'),
        'allowEmpty' => false,
    ),
),

And this is the database field for it (MySQL):

`driversLicenseIsOnline` tinyint(1) unsigned NOT NULL

When I first load a fresh copy of my form, the radio button set is unselected. If I submit the form without doing anything else, when the form reloads, the radio button is filled in as "No" and the validation flash message says "This field cannot be left blank".

The problem goes away when I stop using zero (0) as the value for "No", but I want Cake to store this value as a boolean, not as some other value that I would have to manually translate back and forth to boolean.

How do I stop Cake from automatically filling in a value for this element when it's submitted with no radio selected?

4

4 Answers

1
votes

Stumbled onto this question while searching for the answer myself.

This nasty hack fixed it for me (in CakePHP 2.1 - should work in 1.3):

After you fail to validate, unset the value in $this->request->data if it's empty:

if ($this->Model->save($this->request->data) {
  // data saved
}
else {
  // data failed to save
  // unset radio if empty
  if ($this->request->data['Model']['radio_field'] == "") {
    unset($this->request->data['Model']['radio_field'];
  }
}

Ugh.

0
votes

The way you have your radio buttons set up, there are actually 3 choices:

  1. Nothing selected
  2. 'No' selected
  3. 'Yes' selected

Radio buttons should never have no choice selected (see point #9); (1) above shouldn't happen. So rather than answer your question directly, I'm going to say you should consider using a checkbox instead. Checkboxes are a natural fit for boolean values, and likely more usable in this case.

And Cake will assume you want a checkbox if the database field is tinyint(1), so you could then get rid of the options array in your FormHelper call.

0
votes

Edit: ok, I don't think Cake automatically fill that value with 0, most likely it's a browser behavior. You can test that by debug($this->data) when the saving fails. (Just in case it does, you can unset that value there)

0
votes

So I had a similar problem with a questionnaire, where it would be somewhat semantically correct for radio buttons to remain empty - when a yes or no question remains unanswered. In this case it doesn't seem right like this:

Do you smoke? [yes?]

And this is better:

Do you smoke? (yes)(no)

The way I solved this problem was 'options'=>array(1 => 'No', 2 => 'Yes')