Welcome Guest, Not a member yet? Register   Sign In
set_radio and set_checkbox have problems with value of 0
#1

[eluser]doehoe[/eluser]
This potential bug has been tested in CodeIgniter 1.7.0 and PHP 5.2.5
If you use set_radio and set_checkbox (in the form helper) with the $value parameter set to 0 (zero), it doesn't matter if the checkbox or radio field to which the set_radio or set_checkbox refers, it will never return the checked="checked" if the the checkbox or radio fields were selected.

Two files illustrate:

The controller: problemform.php
Code:
<?php

class ErrorForm extends Controller {
    
    function index()
    {
        $this->load->helper(array('form', 'url'));
        
        $this->load->library('form_validation');
            
        $this->form_validation->set_rules('textfield','','required');
        $this->form_validation->set_rules('radio_1', '', '');
        $this->form_validation->set_rules('check_1', '', '');
            
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('problem_view');
        }
        else
        {
            //success
        }
    }
}
?>

The view: problem_view.php
Code:
<html>
<head>
<title>My Form</title>
</head>
<body>

<?php echo form_open('errorform'); ?>

Text Field:
&lt;input type="text" name="textfield" /&gt;&lt;br /><br />

Radio Choice:
&lt;input type="radio" name="radio_1" value="0" &lt;?=set_radio('radio_1',0) ?&gt;/&gt;Choice 1
&lt;input type="radio" name="radio_1" value="1" &lt;?=set_radio('radio_1',1) ?&gt;/&gt;Choice 2<br /><br />

Checkbox:
&lt;input type="checkbox" name="check_1" value="0" &lt;?=set_checkbox('check_1',0) ?&gt; /&gt;&lt;br /><br />

<div>&lt;input type="submit" value="Submit" /&gt;&lt;/div>

&lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;

To show the problem, run the controller and leave the Text Field blank (in order to generate a validation error). Now try select the "Choice 1" radio selection and click submit. When the form is redisplayed, Choice 1 should be checked, but it is not. But if you choose Choice 2, on submission, Choice 2 will be checked.
Similar for the checkbox. This only occurs because their "value" attributes are 0.

I have identified the problem for set_radio on line 760 of helpers/form_helper.php and on line 812 of libraries/Form_validation.php
Similarly for set_checkbox on line 705 of helpers/form_helper.php and on line 856 of libraries/Form_validation.php
The problem being the double equals ( == ) in
Code:
($field == '' OR $value == '')

Since $field will be 0, and
Code:
0 == ''
resolves to TRUE, the line should be
Code:
($field === '' OR $value === '')
i.e. a triple equals sign.

Please let me know if I should open a bug report.


Messages In This Thread
set_radio and set_checkbox have problems with value of 0 - by El Forum - 12-14-2008, 04:00 PM



Theme © iAndrew 2016 - Forum software by © MyBB