I am having a bit of trouble with my form and radio buttons, with input text I do this:
<?php echo form_input('lastname', set_value('lastname'), 'id=lastname'); ?>
<?php echo form_error('lastname'); ?>
and when the validation runs and that input field that is filled out gets the valued returned...what I am looking for is a way to do this with radio buttons
<tr><td><?php echo form_label('Gender: ', 'gender'); ?></td><td><?php echo form_label('Male', 'male') . form_radio('gender', 'M', '', 'id=male'); ?><br><?php echo form_label('Female', 'female') . form_radio('gender', 'F', '', 'id=female'); ?></td><td><?php echo form_error('gender'); ?></td></tr>
as you can see both my radio buttons have values already F or M.....how do I have the button that is selected returned selected?
The set_value function just sets the value, the only benefit to using it is it simplifies setting the value to an already submitted value when redisplaying the form or showing a default value when the form has yet to be submitted.
Form Helper files basically contains functions which are needed to create different segments of a form (e.g inputbox , submitbutton , dropdown boxes etc.) in CodeIgniter. To use these functions it is needed to load a form helper library.
The set_value() function just sets the value. This function is more useful to preserve the input values when you submit a form with validation errors. So that the user need not to re-enter the fields.
From the user guide: https://www.codeigniter.com/user_guide/helpers/form_helper.html
form_radio()
This function is identical in all respects to the form_checkbox() function above except that is sets it as a "radio" type.
So reading further:
form_checkbox()
Lets you generate a checkbox field. Simple example:
echo form_checkbox('newsletter', 'accept', TRUE);
Would produce:
<input type="checkbox" name="newsletter" value="accept" checked="checked" />
The third parameter contains a boolean TRUE/FALSE to determine whether the box should be checked or not.
So in your case, it might be something like this:
// Pass boolean value to third param
// Example:
$radio_is_checked = $this->input->post('gender') === 'F';
echo form_radio('gender', 'F', $radio_is_checked, 'id=female');
Since set_radio()
just returns a string checked="checked"
, you could wedge it in to the fourth paramter if you really wanted to but it makes for some ugly looking code:
echo form_radio('gender', 'F', NULL, 'id="female" '.set_radio('gender', 'F'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With