开发者

Repopulate radio buttons on failed validation

I have a form that pulls data from a database. Code works fine if it’s an input box but I can’t get the latest $_POST data for radio buttons.

This works for input text box. I get default values pulled from the DB on first load, and I can get the new input (if any) from the user modifies the input box on a failed validation.

<?php echo form_input('email',set_value('email', $email)); ?>

Here’s the code for one of my radio button. It works when I’m pulling data from the DB, but if the form refreshes due to a failed validation, I’m not sure how I can show what the user selected.

<input type="radio" name="gender" value="male" <?php if($gender == "male") echo "checked";  ?> />Male

I played around with set_radio but i ran into the same issue. This works on initial load, but what about on a failed validation? I tried throwing "set_radio" in the second paramter but that didn't work either.

if($gender == "male") {
    echo form_radio('gender开发者_JS百科', 'male',TRUE)
} else {
   echo form_radio('gender', 'male')
}


There seems to be a bug. Unless you include a validation rule for the radio buttons, they do not get repopulated upon postback.

You can include a rule like this.

 $this->form_validation->set_rules('active', 'active', 'required');

if you had..

<div id="active-container">

   <input type="radio" name="active" id="lesson-active" value="1" <?php echo set_radio('active', '1', TRUE); ?> />
   <label for="lesson-active">Active</label>

   <input type="radio" name="active" id="lesson-deactivated" value="2" <?php echo set_radio('active', '2'); ?> />
   <label for="lesson-deactivated">Deactivated</label>

</div>


From the CodeIgniter UserGuide.

<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />

<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />

The first parameter is the name of the radio set, the second is the current radio's value, and the third is an option default if there is no data to populate the field with.


After looking at several code examples, I noticed that the set_radio function HAD TO BE in the value parameter of the form_radio function. Since you can't have an echo within an echo, I created a "hack" by putting an empty string in the value parameter and then appending the set_radio function to it. Here is my example:

echo form_radio('gender', 'M', ''.set_radio('gender', 'M'), $js)."Male ";
echo form_radio('gender', 'F', ''.set_radio('gender', 'F'), $js)."Female ";


Looks like I was able to use the same code as I would for a text box.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜