cakephpcakephp-1.3

CakePHP form helper - change value of hidden input for checkbox/radio


Using CakePHP's form helper to generate a checkbox is easy enough; to use the example from the documentation:

    echo $this->Form->checkbox('done',array('value' => 555));

This will produce the following HTML:

<input type="hidden" name="data[User][done]" value="0" id="UserDone_" />
<input type="checkbox" name="data[User][done]" value="555" id="UserDone" />

This is all well and good, and the hidden field serves to force submission of a value for the "done" field even if the box remains unchecked.

Now, for the sake of argument, let's say the database definition of this field is ENUM('yes','no'). Of course I can easily change the value of the checkbox to "yes". However, if it's unchecked, a value of "0" is submitted from the hidden element. This produces no error or warning from mysql, as 0 is always a legal value for an enum field; it appears as an empty string.

Can I change value of the hidden field that CakePHP generates (to "no"), or do I need to suppress the auto-generation and create the hidden field myself? (An annoyance that grows with the number of checkboxes.)

I believe this all applies to radio button groups, too—at least if they don't have a default selection.

I'm using CakePHP 1.3. Thanks.


Solution

  • Also, you should remember that CakePHP does not support enums (and I am sure this sort of scenario is one reason)

    If your field data is truly binary (yes/no true/false enables/disabled etc.) then for the sake of CakePHP conventions you should just use an int(1) or tinyint(1) field and then convert the boolean value to yes/no etc in the view.

    Then you don't have to worry about creating your own hidden input values and disabling the generated hidden inputs.

    Another option would be to override the form->helper checkbox method that gets called by form->input to accept a new key in the options array that sets the value to something other than a 0 / false.