Welcome Guest, Not a member yet? Register   Sign In
set_radio broken when used for both create AND update. Workarounds?
#1

[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:
&lt;input id='foo1' type='radio' name='foo' value='1' &lt;?php echo set_radio('foo','1');?&gt; /&gt;&lt;label for='foo1'>Option 1</label>
&lt;input id='foo2' type='radio' name='foo' value='2' &lt;?php echo set_radio('foo','2');?&gt; /&gt;&lt;label for='foo2'>Option 2</label>
&lt;input id='foo3' type='radio' name='foo' value='3' &lt;?php echo set_radio('foo','3');?&gt; /&gt;&lt;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:
&lt;input id='foo1' type='radio' name='foo' value='1' &lt;?php if ($my_object-&gt;foo == 1) echo 'checked="checked"'; ?&gt; /><label for='foo1'>Option 1</label>
&lt;input id='foo2' type='radio' name='foo' value='2' &lt;?php if ($my_object-&gt;foo == 2) echo 'checked="checked"'; ?&gt; /><label for='foo2'>Option 2</label>
&lt;input id='foo3' type='radio' name='foo' value='3' &lt;?php if ($my_object-&gt;foo == 3) echo 'checked="checked"'; ?&gt; /><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:
&lt;input id='foo1' type='radio' name='foo' value='1' &lt;?php if (isset($_POST['foo'])) echo set_radio('foo','1'); elseif ($my_object-&gt;foo == 1) echo 'checked="checked"'; ?&gt; /><label for='foo1'>Option 1</label>
&lt;input id='foo2' type='radio' name='foo' value='2' &lt;?php if (isset($_POST['foo'])) echo set_radio('foo','2'); elseif ($my_object-&gt;foo == 2) echo 'checked="checked"'; ?&gt; /><label for='foo2'>Option 2</label>
&lt;input id='foo3' type='radio' name='foo' value='3' &lt;?php if (isset($_POST['foo'])) echo set_radio('foo','3'); elseif ($my_object-&gt;foo == 3) echo 'checked="checked"'; ?&gt; /><label for='foo3'>Option 3</label>

NOT very elegant. Contrast this with a checkbox that does the same thing:

Code:
&lt;input id='bar' type='checkbox' name='bar' value='1' &lt;?php echo set_checkbox('bar',set_value('bar',$my_object-&gt;bar)); ?&gt; />

Simple, easy to read, elegant.

What am I missing? How do you guys do it?




Theme © iAndrew 2016 - Forum software by © MyBB