Currently I am fetching all the values from my database and placing a checkbox next to them. By default all checkboxes are unchecked, but the checkboxes whose id is present in the database should be marked as checked. To do this I have used the following code:
View Class:
<?php if($facilities) foreach($facilities as $facility): ?>
<?php foreach($checked_facility as $key => $value){ ?>
<fieldset id="availablenetworked">
<input type="checkbox" <?php echo ($value['facilities_id'] == $facility['id'] ? 'checked' : ''); ?>
name="facility[]" id="<?php echo $facility['id'] ?>" value="<?php echo $facility['id'] ?>">
<label for="<?php echo $facility['id'] ?>"><?php echo $facility['title'] ?></label>
</fieldset>
<?php } endforeach; ?>
Doing this correctly checkmarks all the values that I have in my database, but messes up my view and makes it look like this:
$facilities
is used to fetch all records of facilities and $checked_facility
is used to check the values that a specific person has chosen.
The response returned from $checked_facility looks like this where I'm trying to access the facilities_id and marking all those with a checkmark in my list.
My Answer:
php
class View {
public function displayCheckboxes($valuesFromDatabase, $allValues) {
foreach ($allValues as $value) {
$checked = in_array($value['id'], $valuesFromDatabase) ? 'checked' : '';
echo '' . $value['name'] . '
';
}
}
}
?>
In the above code, the `displayCheckboxes` method takes two parameters: `$valuesFromDatabase` which is an array of ids present in the database, and `$allValues` which is an array of all values fetched from the database. It then loops through all values and checks if the id is present in the `$valuesFromDatabase` array. If it is present, the checkbox is marked as checked.
Rate this post
3 of 5 based on 3605 votesComments