문제

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?

도움이 되었습니까?

해결책

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
));

다른 팁

Try the following:

<?php echo $this->Form->input('fieldName', array(
                            'type' => 'radio',
                            'hiddenField' => false,
                            'options' => array('value1' => 'option label1'))
                        )); ?>
<?php echo $this->Form->input('fieldName', array(
                            'type' => 'radio',
                            'hiddenField' => false,
                            'options' => array('value2' => 'option label2'))
                        )); ?>
<?php echo $this->Form->input('fieldName', array(
                            'type' => 'radio',
                            'hiddenField' => false,
                            'options' => array('value3' => 'option label3'))
                        )); ?>

Hope this works.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top