Gopal Aggarwal Gopal Aggarwal - 5 months ago 20
PHP Question

CakePHP FormHelper radio buttons (or checkboxes) only last button's value is being submitted

Background

Using CakePHP's FormHelper, I am creating multiple radio buttons, each being rendered by separate calls to input(), to allow for HTML to be used in-between the radio buttons.

Issue

When the form is submitted, only the last radio button's value is being submitted to server.

// preselect radio button if appropriate
$selected = isset($this->request->data['ModelName']['field']) ? $this->request->data['ModelName']['field'] : null ;

// output the radio button
echo $this->Form->input('field', array(
'type' => 'radio',
'options' => array(1 => 'Option A',),
'class' => 'testClass',
'selected' => $selected,
'before' => '<div class="testOuterClass">',
'after' => '</div>',
));


Requirement

How to get all radio buttons (or checkboxes) created using FormHelper to submit values correctly?

Answer

For certain input types (checkboxes, radios) a hidden input is created so that the key in $this->request->data will exist even without a value specified.

If you want to create multiple blocks of inputs on a form that are all grouped together, you should use this parameter on all inputs except the first. If the hidden input is on the page in multiple places, only the last group of input’s values will be saved. (Documentation)

Thus, for your task, pass 'hiddenField' => false, as an option to all calls to input() for that group's radio button (or checkbox) except the first one. In this example, we have it by the name 'field'.

e.g.

echo $this->Form->input('field', array(
    'type' => 'radio',
    'options' => array(1 => 'Option A',),
    'class' => 'testClass',
    'selected' => $selected,
    'before' => '<div class="testOuterClass">',
    'after' => '</div>',
    'hiddenField' => false, // added for non-first elements
));