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

12,798

Solution 1

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.

Solution 2

With FormHelper::checkbox, you can use hiddenField to set the default value.

<?php echo $this->Form->checkbox('done', array('value'=>'yes', 'hiddenField'=>'no');?>

With FormHelper::radio, you can only set value to default to one of the options, if the values match. This will also suppress the hidden field.

<?php echo $this->Form->radio('done', array('yes' => __('Yes')), 'no' => __('No'), array('value'=>'no');?>

Solution 3

Unfortunately, FormHelper::checkbox allows you to disable the hidden element, but not to select its value, so you will need to do so and create the hidden field yourself. For example:

<?php echo $this->Form->hidden('done',array('value'=>'no'))?>
<?php echo $this->Form->checkbox('done',array('value'=>'yes','hiddenField'=>false))?>
Share:
12,798
eaj
Author by

eaj

Nerd nomad.

Updated on June 18, 2022

Comments

  • eaj
    eaj almost 2 years

    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.