CakePHP Undefined radio button changed to unwanted value to send

I have this form element:

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

This is a 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 upload a new copy of my form, the radio button set is not selected. If I submit the form without any action, when the form reloads, the radio button fills in as "No", and the verification flash message says: "This field cannot be empty."

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

How to stop Cake from automatically filling in the value for this item when sending it without selecting a radio?

+4
source share
4 answers

I came across this question, looking for the answer itself.

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

After you do not check, disable the value in $ this-> request-> data if it is 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.

+1
source

How you set up your radio buttons, there are actually 3 options:

  • Nothing selected
  • No selected
  • 'Yes' selected

Radio buttons should never have been selected (see paragraph 9); (1) the above should not occur. Therefore, instead of directly answering your question, I will say that you should use the checkbox. Flags are a natural fit for Boolean values ​​and are probably more suitable for use in this case.

And Cake will assume that you want to check the box if the database field is tinyint (1), so you could get rid of the array of parameters in your FormHelper call.

0
source

Thus, I had a similar problem with the questionnaire, where it would be somewhat semantically correct if the radio buttons remain blank - when the question β€œyes” or β€œno” remains unanswered. In this case, it looks wrong:

Do you smoke? [Yes?]

And this is better:

Do you smoke? (Well no)

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

0
source

Edit: ok, I don’t think Cake will automatically fill this value with 0, most likely this is browser behavior. You can verify this by debugging ($ this-> data) when a crash is not possible. (Just in case, you can disable this value)

0
source

All Articles