开发者

CodeIgniter - Setting Checkbox/Radio values from SQL query

I'm trying to create an edit page, which brings all of the original values from the database in at first, then let's the form_validation library take over afterwards. I have managed to get everything working as intended but checkboxes and radio buttons.

Here's an example of my form, pretty generic...

    <input type="checkbox" name="protocols[]" value="online" <?php echo set_checkbox('protocols[]', 'online');?> /> 
    <input type="checkbox" name="protocols[]" value="network" <?php echo set_checkbox('protocols[]', 'network');?> />
    <input type="checkbox" name="protocols[]" 开发者_高级运维value="splitscreen" <?php echo set_checkbox('protocols[]', 'splitscreen');?> />

The database values return as a comma separated string (online,splitscreen).

I also have another 3 field checkbox array to populate, a 9 field checkbox field, and a 3 field radio section to fill.

Any help would be greatly appreciated, thanks.


Remove the brackets from the field name in your call to set_checkbox():

<input type="checkbox" name="protocols[]" value="online" <?php echo set_checkbox('protocols', 'online');?> /> 
<input type="checkbox" name="protocols[]" value="network" <?php echo set_checkbox('protocols', 'network');?> />
<input type="checkbox" name="protocols[]" value="splitscreen" <?php echo set_checkbox('protocols', 'splitscreen');?> />

The form validation library will take care of checking the box or not, but it responds to the $_POST array only, so you'll have to use the third parameter to get the inputs checked by default:

set_checkbox()

Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).

Not a great explanation, but here's an example. First get your values from the comma separated string:

The database values return as a comma separated string (online,splitscreen).

// Something like this
$values = explode(',', $my_data); // Now it's an array

Then check if each checkbox's value is in that array:

<?php echo set_checkbox(
    'protocols',
    'splitscreen',
    in_array('splitscreen', $values) // TRUE checks the box, FALSE does not
);?>

I'd do this in a loop for convenience reasons if nothing else. It's also worth looking at form_checkbox() which will make this a good deal easier.

See user guide for details: http://ellislab.com/codeigniter/user_guide/helpers/form_helper.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜