I was trying out CodeIgniter’s Form Helper the other day. I came across one issue with form_radio. I could not get the submitted results to display properly. I’m using radio buttons to show a priority with a range that goes from 1 to 5. I tried several suggestions from the CodeIgniter’s Forum, but none of them seem to work. This article discusses an alternative way to get form_radio to display submitted data properly.
First of all, let’s go through the basics.
The Basics
To load CodeIgniter’s Form Helper, we will add this code to our controller.
$this->load->helper(‘form’);
Once the form helper is loaded, we can now start using the built-in functions like:
echo form_open(’email/send’);
which is similar to:
<form method=”post” action=”http:/example.com/email/send” />
Form_Radio
Here’s the form_radio function:
echo form_radio(‘var’, ‘1’, TRUE);
Which is similar to:
<input type=”radio” name=”var” value=”1″ checked=”checked” />
My Code
echo form_radio(‘var’, ‘1’, set_radio(‘var’, ‘1’));
echo form_radio(‘var’, ‘2’, set_radio(‘var’, ‘2’));
echo form_radio(‘var’, ‘3’, set_radio(‘var’, ‘3’));
echo form_radio(‘var’, ‘4’, set_radio(‘var’, ‘4’));
echo form_radio(‘var’, ‘5’, set_radio(‘var’, ‘5’));
But, this code doesn’t seem to display the submitted value properly.
Suggestions
Here’s a couple of suggestions from the User Guide:
echo form_radio(‘var’, ‘1’, set_radio(‘var’, ‘1’));
Or
<input type=”radio” name=”var” value=”1″ <?php echo set_radio(‘var’, ‘1’, TRUE); ?> />
Both examples didn’t work for me. I ended up using the code below.
Solution
By the way, the variable “$row->var” is the submitted data.
<input type=”radio” name=”var” value=”1″ <?php if ($row->var==’1′) echo ‘checked=”checked”‘; ?> />1
I could use a ternary as well …
<input type=”radio” name=”var” value=”1″ <?php echo ($row->var==’1’) ? ‘checked=”checked”‘ : ”; ?> />1
Final Code
Here’s my final code.
<input type=”radio” name=”var” value=”1″ <?php if ($row->var==’1′) echo ‘checked=”checked”‘; ?> />1
<input type=”radio” name=”var” value=”1″ <?php if ($row->var==’2’) echo ‘checked=”checked”‘; ?> />2
<input type=”radio” name=”var” value=”1″ <?php if ($row->var==’3’) echo ‘checked=”checked”‘; ?> />3
<input type=”radio” name=”var” value=”1″ <?php if ($row->var==’4’) echo ‘checked=”checked”‘; ?> />4
<input type=”radio” name=”var” value=”1″ <?php if ($row->var==’5’) echo ‘checked=”checked”‘; ?> />5
The end result is, only one radio button is selected based on submmited data. There is nothing like using some old-fashioned PHP and HTML markup to display submitted data properly.