user1881482 user1881482 - 7 months ago 6
HTML Question

Adding checked variable from database with fields from database as well

I have a form which has a list of checkboxes to be filled in on insert to database as well as when editing. When editing I am trying to populate the fields with a list of fields from the database which is in the

$groups
variable and the checked value being checked against the
group_id
from groups with the
group_id
from the
$user
. It is working except it only fills out one checkbox and some users belong to multiple groups. Any ideas, or more efficient ways to do this.

Heres my code so far

<?php foreach($groups as $group) : ?>
<?php foreach ($user['groups'] as $uG) {
if ($uG['group_id'] == $group['id']) {
$checked = "checked";
} else {
$checked = '';
}
}?>

<div class="checkbox">
<label for="group_id-<?php echo $group['id']; ?>">
<input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
<?php echo $group['name']; ?>
</label>
</div>
<? endforeach; ?>

Answer

This problem is that you are searching all the $users['group'] array and not stopping when you find a match, so unless last $uG['group_id'] matches $group['id'] you continue and therefore clear $checked after potentially setting it.

So just add a break when you find a match.

Also, officially the correct way of setting the checked status is checked="checked" although most modern browsers are not that pedantic, its possibly better to stick to the HTML spec

<?php foreach($groups as $group) : ?>
    <?php 
     $checked = '';
     foreach ($user['groups'] as $uG) {
        if ($uG['group_id'] == $group['id']) {
            $checked = 'checked="checked"';
            break;
        }               
    }?>

    <div class="checkbox">
        <label for="group_id-<?php echo $group['id']; ?>">
            <input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
            <?php echo $group['name']; ?>
        </label>
    </div>           
 <? endforeach; ?>

you could also use a ternary operator and in_array() to do this all in one simple statement

<?php 
    foreach($groups as $group) : 
        $checked = in_array( $group['id'], $user['groups'] ) ? 'checked="checked"' : '';
?>    
    <div class="checkbox">
        <label for="group_id-<?php echo $group['id']; ?>">
            <input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
            <?php echo $group['name']; ?>
        </label>
    </div>           
 <? endforeach; ?>
Comments