[eluser]pbarney[/eluser]
This should be very simple, and either I'm missing something, or CodeIgniter is missing set_radio function that works well.
Consider the following example:
A user enters a new record into a form that includes a radio button:
Code:
<input id='foo1' type='radio' name='foo' value='1' <?php echo set_radio('foo','1');?> /><label for='foo1'>Option 1</label>
<input id='foo2' type='radio' name='foo' value='2' <?php echo set_radio('foo','2');?> /><label for='foo2'>Option 2</label>
<input id='foo3' type='radio' name='foo' value='3' <?php echo set_radio('foo','3');?> /><label for='foo3'>Option 3</label>
Simple enough... if the form fails validation, the checked="checked" attribute for 'foo' will be set if the user previously checked it. No problem.
BUT, I use this view to both <b>add</b> a record <i>and</i> to display an <b>existing</b> record. So to display an existing record, I load all of the form values into a variable and display the form. <b>Since there hasn't been a POST yet, set_radio does nothing.</b> So it won't work.
So to display the form when <i>updating</i>, our code has to look like this:
Code:
<input id='foo1' type='radio' name='foo' value='1' <?php if ($my_object->foo == 1) echo 'checked="checked"'; ?> /><label for='foo1'>Option 1</label>
<input id='foo2' type='radio' name='foo' value='2' <?php if ($my_object->foo == 2) echo 'checked="checked"'; ?> /><label for='foo2'>Option 2</label>
<input id='foo3' type='radio' name='foo' value='3' <?php if ($my_object->foo == 3) echo 'checked="checked"'; ?> /><label for='foo3'>Option 3</label>
But if I want to handle BOTH cases (handling a previously-posted form AND filling a form with existing data), I need to do the following:
Code:
<input id='foo1' type='radio' name='foo' value='1' <?php if (isset($_POST['foo'])) echo set_radio('foo','1'); elseif ($my_object->foo == 1) echo 'checked="checked"'; ?> /><label for='foo1'>Option 1</label>
<input id='foo2' type='radio' name='foo' value='2' <?php if (isset($_POST['foo'])) echo set_radio('foo','2'); elseif ($my_object->foo == 2) echo 'checked="checked"'; ?> /><label for='foo2'>Option 2</label>
<input id='foo3' type='radio' name='foo' value='3' <?php if (isset($_POST['foo'])) echo set_radio('foo','3'); elseif ($my_object->foo == 3) echo 'checked="checked"'; ?> /><label for='foo3'>Option 3</label>
NOT very elegant. Contrast this with a checkbox that does the same thing:
Code:
<input id='bar' type='checkbox' name='bar' value='1' <?php echo set_checkbox('bar',set_value('bar',$my_object->bar)); ?> />
Simple, easy to read, elegant.
What am I missing? How do you guys do it?